ES Modules (ESM) and Gatsby
Examples
Introduction
The ECMAScript module (ESM) format is the official TC39 standard for packaging JavaScript. For many years, CommonJS (CJS) was the de facto standard in Node.js. You can author gatsby-config and gatsby-node in ESM syntax.
This feature was added in gatsby@5.3.0.
Prerequisites
- A Gatsby project set up with
gatsby@5.3.0or later. (Need help creating one? Follow the Quick Start)
Usage in Gatsby
Generally speaking you need to follow the official standard as explained in the Node.js documentation.
gatsby-config
Create a gatsby-config.mjs file. Here’s an example gatsby-config using ESM syntax:
gatsby-node
Create a gatsby-node.mjs file and use any of the Node APIs as usual. Here’s an example gatsby-node using ESM syntax:
Migrating from CommonJS to ES Modules
Use
import/exportsyntax instead ofrequire/module.exportsFile extensions in imports are mandatory
You can replicate the
__dirnamecall withimport.meta.url:You can replicate
require.resolvewithcreateRequire:
The documents Interopability with CommonJS and Differences between ES Modules and CommonJS also apply to ESM in Gatsby.
Here’s how you’d migrate a gatsby-config.js file to gatsby-config.mjs.
Before:
After:
Current limitations
The TypeScript variants of
gatsby-configandgatsby-nodedo not support ESM yet. We plan on adding support in a future minor release by using the.mtsextension. If you have questions or suggestions about this, please go to our ESM in Gatsby files umbrella discussion.However, you can use Type Hinting in the meantime.
The ESM in Gatsby files umbrella discussion is also the right place for any questions about the .mjs usage.