Using ES6 Module Syntax in Gatsby API Files
The purpose of this recipe is to demonstrate how to use ES6 module syntax in Gatsby API files on Gatsby Cloud. Gatsby API files include:
- gatsby-node.js
- gatsby-config.js
- gatsby-browser.js
- gatsby-ssr.js
NOTE: This approach does not apply to gatsby-browser.js
This recipe assumes:
- you already have a Gatsby project
- you are familiar with the
esm
library
The set-up will use gatsby-node.js
as an example. However, the approach is the same for all Gatsby API files.
Set-up
First add esm
as a dependency to your Gatsby project.
npm install esm
Now consider the following CommonJS module gatsby-node.js
:
// gatsby-node.js
const _ = require("lodash")
exports.onPreInit = gatsbyNodeHelpers => {
const { reporter } = gatsbyNodeHelpers
reporter.info("This message is from the onPreInIt lifecycle")
reporter.info(_.isString("Is this a string?"))
}
Next rename your gatsby-node.js
file to gatsby-node.esm.js
. Then refactor the contents of the file to ES6 module syntax.
// gatsby-node.esm.js
import { isString } from "lodash"
export const onPreInit = gatsbyNodeHelpers => {
const { reporter } = gatsbyNodeHelpers
reporter.info("This message is from the onPreInIt lifecycle")
reporter.info(isString("Is this a string?"))
}
Now create a new gatsby-node.js
file and add the following content:
// gatsby-node.js
const requireEsm = require('esm')(module);
module.exports = requireEsm('./gatsby-node.esm.js');
Comments
0 comments
Please sign in to leave a comment.