获取当前ES模块的文件名

Get the file name of the current ES module

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

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

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

一个可能的解决方案: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();
}

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

您正在寻找 (proposed) import.meta 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())
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__dirname.

zx 脚本运行器