0

I'm aware that, when using ES modules, __filename and __dirname don't exist.

This is clearly stated in Node.js documentation, and also alternatives can be found in several places, like this answer.

What I'm missing here is the cause of this behavior. Why are these variables not available in ES modules?

I could not find an explanation on SO or in the Node docs.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
cdpaiva
  • 93
  • 1
  • 7

1 Answers1

2

When re-using the same code between a browser, Node.js, d8, Babel, etc., the notion of what the filename is and what it means may be different based on how you're using it, and where the file is being served from. Filenames may not be relevant the same way when served from a webserver or when packed by a bundler, or interpreted by a shell.

And so in an effort to standardize this across those "platforms", ES modules come from URLs not filenames, and import.meta.url exists as replacement functionality.

Wyck
  • 10,311
  • 6
  • 39
  • 60