获取当前ES模块的文件名

问题描述 投票:0回答:3

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

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

如果没有,为什么不呢?沙箱等

javascript ecmascript-6 es6-modules
3个回答
15
投票

您正在寻找 (proproped)

import.meta
元属性。这个对象到底包含什么取决于环境,但在浏览器中你可以使用

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

您可以通过使用

URL
接口解析文件名来提取文件名,例如

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

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);

...另一个例子:

import { fileURLToPath, URL } from "node:url";

const rootDir = fileURLToPath(new URL("..", import.meta.url));

或者,使用

zx
脚本运行程序来设置
__filename
__dirname


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.