6

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

smnbbrv
  • 23,502
  • 9
  • 78
  • 109
Andrew
  • 321
  • 2
  • 11
  • When running JS in a browser, you can't have any information on the server, since it is ran locally by the client's browser. Why do you need that information ? Maybe you are missing something, or haven't found a proper solution to a problem you have. – Seblor Dec 22 '17 at 09:09
  • yes it is, but can i get this paths during webpack processing as strings in final bundle like webpack plugin DefinePlugin to pass process.env to bundle? – Andrew Dec 22 '17 at 09:13
  • You can try `module.i` and `module.children`. This worked in my React app. – Nandu Kalidindi Dec 22 '17 at 09:15
  • @Andrew what is the problem you are trying to solve? Currently it looks like you are doing something wrong – smnbbrv Dec 22 '17 at 09:35

2 Answers2

9

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)

Klesun
  • 12,280
  • 5
  • 59
  • 52
8

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 e.g. Current file path in webpack or Webpack can not use __dirname?.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    As of writing this, things have progressed and various browsers now implement import.meta https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta#Syntax – Stefnotch Jan 05 '19 at 20:38