【Gatsby.js】How to Fix ReferenceError: __dirname is not defined in ES module scope
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
ReferenceError: __dirname is not defined in ES module scope
This article summarizes how to fix this error.
Background
In a Gatsby.js config file, I needed to use import
.
To achieve this, I renamed gatsby.config.js
to gatsby.config.mjs
. This change required modifying the way relative paths were written.
Conclusion
In an ES module,
__dirname
cannot be used. Instead, use the following approach:
path: new URL("./content/thumbnail", import.meta.url).pathname,
After rewriting it this way, everything worked fine.
For reference, the original code was:
path: `${__dirname}/content/thumbnail`,
Additional Notes
In Node.js, there are two JavaScript module systems: CommonJS and ES Module.
By default, CommonJS is used unless:
- The file extension is
.mjs
, or - The
package.json
contains"type": "module"
To explicitly use CommonJS, you can rename the file to .cjs
.
The following code:
import.meta.url
retrieves the absolute URL of the module.
By using the URL
class to format it, we can obtain the expected path:
new URL("./content/thumbnail", import.meta.url).pathname
For conversions and compatibility issues like this, AI tools are incredibly useful—even with rough prompts, they often provide great solutions. Much appreciated!