ES6 获取模块内部模块路径

ES6 get path of module inside module

如何获取模块内部的模块路径?我使用 babel 和 webpack 为 browsers.

创建包

我期待

/src/someModule/index.js

console.log(`someModule path is ${process.execPath}`);

浏览器中输出 someModule path is /home/user/proj/src/someModule

someModule path is /src/someModule

无法访问 ES6 模块内的模块路径(目前)。这是一个known problem, and there's a stage 3 proposal for a new meta property import.meta that resolves to an object with the respective information. Read more about that here.

也就是说,webpack 打包器 可以 support Node's __dirname, see e.g. Current file path in webpack or Webpack can not use __dirname?.

现在所有现代浏览器都支持 import.meta,耶!

// /es6/someFile.js
console.log(import.meta);

输出:

{url: "https://yourdomain.com/es6/someFile.js"}

(尽管 OP 询问了 webpack,但我相信这个信息对很多来这里的人都有用)