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

后端 未结 10 863
南笙
南笙 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: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.

提交回复
热议问题