How to fix "__dirname is not defined in ES module scope"
Published on
Last updated on
1 min read • --- views
Problem
I ran into this error when using __dirname in an ES module.
__dirname is an environment variable that tells you the absolute path of the directory containing the currently
executing file, and many Node.js projects use this.
But if you use it inside an ES module, you can't use it because of the infamous "__dirname is not defined in ES module scope" an error appears.
Solution
What can you do in this case?
To get the current file directory, we'll want to use a combination of a global variable and a few built-in methods:
import.meta.urlto get the current file's as a URLurl.fileURLToPathto change the URL to a pathpath.dirnameto get the directory name
Using these methods, we can reconstruct the global __dirname and __filename variables:
import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename);
Now you can use __dirname as usual:
console.log(__dirname)
Conclusion
Due to the different approaches to modularity in Node.js and EcmaScript, you may encounter such problems.
For further reading, check out the Node.js documentation for __dirname.
You might also like:
Semantic Versioning in npm
--- views
A friendly, practical guide to SemVer in npm. Learn versioning rules, avoid dependency chaos, and manage updates with confidence.
Node Version Manager
--- views
NVM, or Node Version Manager. What is it and why we should use it?
How to decrease deployment time by 44% with pnpm
--- views
Learn how to efficiently migrate your project from npm to pnpm with this guide.
Share it: