How to Fix the “__dirname is not defined in ES module scope” Error
If you encounter the “__dirname is not defined in ES module scope” error while using __dirname
in an ES module, here’s how you can fix it.
In a Node script, __dirname
is used to retrieve the path of the folder where the current JavaScript file resides. However, it cannot be used within an ES module, leading to the aforementioned error.
To overcome this issue, follow these steps:
- Import the Node.js
path
module and thefileURLToPath
function from theurl
module:
1 | import path from 'path'; |
- Replicate the functionality of
__dirname
using the following code:
1 | const __filename = fileURLToPath(import.meta.url); |
This code snippet also replicates __filename
, which returns the filename of the executed code.
- Finally, you can use
__dirname
as you normally would:
1 | console.log(__dirname); |
By following these steps, you can resolve the “__dirname is not defined in ES module scope” error and continue using __dirname
within your ES module.
tags: [“JavaScript”, “Node.js”, “ES module”, “__dirname error”, “technical blog”]