【问题标题】:Get the file name of the current ES module获取当前ES模块的文件名
【发布时间】:2019-08-26 19:22:21
【问题描述】:

是否可以获取当前 JavaScript module 的文件名?

// item.mjs
function printName() {
  console.log(...);  // >> item or item.mjs
};

如果不是,为什么不呢?沙盒等。

【问题讨论】:

  • 在 Node.js 中它只是 __filename__。如果您正在寻找客户端解决方案,请参阅this answer
  • @PatrickRoberts 谢谢,但我不是在谈论 Node.js 文件。
  • 你说的是加载了脚本标签的文件还是你正在使用一些js框架,你需要文件名?
  • @MahendraPratap 我说的是使用脚本标签(即<script src="item.mjs" type="module"></script>)导入的 JavaScript 模块。
  • @isar 客户端 ES6 模块没有转译步骤?那么你肯定也足够勇敢地使用this experimental feature :-)

标签: javascript ecmascript-6 es6-modules


【解决方案1】:

您正在寻找 (proposed) import.meta 元属性。这个对象的具体内容取决于环境,但在浏览器中您可以使用

// item.mjs
function printName() {
  console.log(import.meta.url);  // https://domain.example/js/item.mjs
}

您可以通过使用URL interface 解析来提取文件名,例如

console.log(new URL(import.meta.url).pathname.split("/").pop())

【讨论】:

    【解决方案2】:

    一个可能的解决方案:mjs 文件中的每个方法都可以设置一个全局变量,该变量将是模块的名称。然后printName() 方法将打印该全局变量的当前值。这样,在处理时,您可以检查该全局变量的当前状态以获取当前正在执行的文件的名称。

    全局js

    var global_mjs_name = 'none';
    
    function printName() {
       console.log('processed in ' + global_mjs_name);
    }
    
    window.addEventListener('DOMContentLoaded', function(event){
        printName(); // output -> 'none'
        doWork({}); 
        printName(); // output -> 'item.mjs'
        doFunStuff();
        printName(); // output -> 'FunStuff.mjs'
    });
    

    在 item.mjs 中:

    const item_js_name = 'item.mjs';
    
    function doWork(data) {
       global_mjs_name = item_js_name; // every time you execute code within the module, update the global variable
       return processData(data);
    }
    

    在另一个名为 FunStuff.mjs 的模块中

    const funstuff_js_name = 'FunStuff.mjs';
    
    function doFunStuff() {
       global_js_name = funstuff_js_name; // update the global variable for the module
       return haveFun();
    }
    

    我并不是说这是完成这项任务的最佳方式。手动处理全局变量的更改可能会很痛苦。

    【讨论】:

      【解决方案3】:
      import { basename, dirname } from "node:path";
      import { fileURLToPath } from "node:url";
      
      const __filename = fileURLToPath(import.meta.url);
      const __dirname = dirname(__filename);
      
      const filename = basename(__filename);
      

      或者,使用设置__filename__dirnamezx 脚本运行器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-10
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 2012-12-21
        • 1970-01-01
        • 1970-01-01
        • 2011-08-18
        相关资源
        最近更新 更多