How to get the file-path of the currently executing javascript code

后端 未结 10 746
南笙
南笙 2020-11-29 19:18

I\'m trying to do something like a C #include \"filename.c\", or PHP include(dirname(__FILE__).\"filename.php\") but in javascript. I know I can do

相关标签:
10条回答
  • 2020-11-29 19:37

    I've more recently found a much cleaner approach to this, which can be executed at any time, rather than being forced to do it synchronously when the script loads.

    Use stackinfo to get a stacktrace at a current location, and grab the info.file name off the top of the stack.

    info = stackinfo()
    console.log('This is the url of the script '+info[0].file)
    
    0 讨论(0)
  • 2020-11-29 19:39

    I may be misunderstanding your question but it seems you should just be able to use a relative path as long as the production and development servers use the same path structure.

    <script language="javascript" src="js/myLib.js" />
    
    0 讨论(0)
  • 2020-11-29 19:46

    Refining upon the answers found here I came up with the following:

    getCurrentScript.js

    var getCurrentScript = function () {
      if (document.currentScript) {
        return document.currentScript.src;
      } else {
        var scripts = document.getElementsByTagName('script');
        return scripts[scripts.length-1].src;
    
      }
    };
    
    module.exports = getCurrentScript;
    

    getCurrentScriptPath.js

    var getCurrentScript = require('./getCurrentScript');
    
    var getCurrentScriptPath = function () {
      var script = getCurrentScript();
      var path = script.substring(0, script.lastIndexOf('/'));
      return path;
    };
    
    module.exports = getCurrentScriptPath;
    

    BTW: I'm using CommonJS module format and bundling with webpack.

    0 讨论(0)
  • 2020-11-29 19:47

    Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,

    <script type=text/javascript src='/dir/jsfile.js'></script>

    or

    <script type=text/javascript src='../../scripts/jsfile.js'></script>

    If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path

    0 讨论(0)
提交回复
热议问题