如何解决Gatsby项目中的ERR_REQUIRE_ESM错误?
Gatsby 搭建博客时 ERR_REQUIRE_ESM 错误解决方法
问题背景
操作系统:Windows 10
使用Gatsby搭建博客,修改gatsby-config.js启用gatsby-transformer-remark及相关插件后,出现ERR_REQUIRE_ESM错误。已尝试重装node-fetch、修改package.json中type为module,均未解决。
修改前的gatsby-config.js
module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ { resolve: 'gatsby-plugin-typescript', options: { isTSX: true, allExtensions: true, }, }, `gatsby-plugin-emotion`, `gatsby-plugin-react-helmet`, // { // resolve: `gatsby-source-filesystem`, // options: { // name: `contents`, // path: `${__dirname}/contents`, // }, // }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: <https://gatsby.dev/offline> // `gatsby-plugin-offline`, ], };
修改后的gatsby-config.js
module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ { resolve: 'gatsby-plugin-typescript', options: { isTSX: true, allExtensions: true, }, }, `gatsby-plugin-emotion`, `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `contents`, path: `${__dirname}/contents`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: 'gatsby-remark-smartypants', options: { dashes: 'oldschool', }, }, { resolve: 'gatsby-remark-prismjs', options: { classPrefix: 'language-', }, }, { resolve: 'gatsby-remark-images', options: { maxWidth: 768, quality: 100, withWebp: true, }, }, { resolve: 'gatsby-remark-copy-linked-files', options: {}, }, { resolve: 'gatsby-remark-external-links', options: { target: '_blank', rel: 'nofollow', }, }, ], }, }, ], };
解决步骤
1. 降级ESM格式的插件
ERR_REQUIRE_ESM核心原因是新增的部分插件已转为纯ESM模块,而Gatsby配置文件采用CommonJS格式无法兼容。重点排查gatsby-remark-external-links,该插件最新版本为ESM格式,需降级到支持CommonJS的版本:
npm install gatsby-remark-external-links@^0.0.4
2. 锁定node-fetch版本
部分Gatsby插件依赖node-fetch,v3+版本为纯ESM会引发冲突,强制安装v2.x版本:
npm install node-fetch@^2.6.7
3. 恢复package.json的type配置
不要将package.json中的type设为module,Gatsby核心配置文件仅支持CommonJS格式,修改后会导致配置加载失败。
4. 清理缓存并重装依赖
执行以下命令彻底清理缓存和旧依赖,重新安装:
gatsby clean rmdir /s node_modules # Windows命令,Linux/macOS用 rm -rf node_modules del package-lock.json # Windows命令,Linux/macOS用 rm package-lock.json npm install npm run develop
5. 验证插件版本兼容性
检查所有gatsby-remark-*插件的版本,确保与当前使用的Gatsby主版本匹配,确认插件是否支持CommonJS环境。
内容的提问来源于stack exchange,提问作者이수환
相关产品推荐
相关产品推荐

