简体   繁体   中英

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 .

I expect

/src/someModule/index.js

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

to output in browser someModule path is /home/user/proj/src/someModule

or someModule path is /src/someModule

There is no way to access the module path inside an ES6 module (yet). 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. 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? .

The import.meta is now supported in all modern browsers, yay!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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