【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
Summary on how to fix ReferenceError: __dirname is not defined in ES module scope.
Error Details
ReferenceError: __dirname is not defined in ES module scopeBackground
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,
__dirnamecannot 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.jsoncontains"type": "module"
To explicitly use CommonJS, you can rename the file to .cjs.
The following code:
import.meta.urlretrieves 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).pathnameFor conversions and compatibility issues like this, AI tools are incredibly useful—even with rough prompts, they often provide great solutions. Much appreciated!





