DEV Community

LG
LG

Posted on

2 2

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay