DEV Community

LG
LG

Posted on

CJS's __dirname & __filename for ESM – beginners friendly constants

Okay, you switched from CJS to more standard of ES6, you potentially lost ability to use __constants such as __dirname (most often used) or __filename , you need mock ones from ESM perspective, let's make default export utility lib :

// Within esm-constants.js do : export default (function(){ import path, {dirname} from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) }()) // At the very top of some-other-module.js scope do the following:  // import './path/to/esm-constants.js' 
Enter fullscreen mode Exit fullscreen mode

That's it , you're ready to go !

p.s. this snippet flows around web for a while, just tried to capture & emphasize this as a MUST listing in Node-series of mine.

Thanks & see you in the next one !

Top comments (0)