简体   繁体   English

ES6 获取模块内模块的路径

[英]ES6 get path of module inside module

How can i get moudle path inside module?我怎样才能获得模块内的模块路径? I use babel and webpack to create bundle for browsers .我使用 babel 和 webpack 为浏览器创建包。

I expect我预计

/src/someModule/index.js /src/someModule/index.js

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

to output in browser someModule path is /home/user/proj/src/someModule浏览器中输出someModule path is /home/user/proj/src/someModule

or someModule path is /src/someModulesomeModule path is /src/someModule

There is no way to access the module path inside an ES6 module (yet).目前还没有办法访问 ES6 模块内的模块路径。 This is a 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.这是一个已知问题,并且有一个关于import.meta属性import.meta第 3 阶段提案,该属性解析为具有相应信息的对象。 Read more about that here .在此处阅读更多相关信息。

That said, the webpack bundler does support Node's __dirname , see eg Current file path in webpack or Webpack can not use __dirname?也就是说,webpack bundler确实支持 Node 的__dirname ,参见例如webpackWebpack 中的当前文件路径不能使用 __dirname? . .

The import.meta is now supported in all modern browsers, yay!现在所有现代浏览器都支持import.meta是的!

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

Outputs:输出:

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

(even though OP asked about webpack, I believe this info will be useful for many people coming here) (尽管 OP 询问了 webpack,但我相信这个信息对很多来这里的人有用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM