You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gatsby集成remark-gfm遇ES模块导入错误,动态导入仍无效求助

解决Gatsby中使用remark-gfm的ESM模块兼容问题

问题根源

错误提示指向gatsby-config.js中的ESM模块导入问题——Gatsby会将gatsby-config和gatsby-node编译为CommonJS模块,但remark-gfm是纯ES模块,直接同步导入会触发require()不支持ESM的错误,而非你修改的gatsby-node代码本身。

解决方案

1. 修正gatsby-config中的插件配置

如果你的gatsby-config里直接同步导入了remark-gfm并传入gatsby-plugin-mdx的配置,比如:

import remarkGfm from 'remark-gfm'

export default {
  plugins: [
    {
      resolve: 'gatsby-plugin-mdx',
      options: {
        remarkPlugins: [remarkGfm]
      }
    }
  ]
}

这种写法会被编译为CommonJS的require调用,触发错误。需改为异步动态导入:

export default {
  plugins: [
    {
      resolve: 'gatsby-plugin-mdx',
      options: {
        remarkPlugins: [
          // 用异步函数动态导入ESM模块
          async () => (await import('remark-gfm')).default
        ]
      }
    }
  ]
}

2. 调整gatsby-node中的代码

确保动态导入的写法正确,注意取出模块的default导出:

// 改用动态导入
const { compileMDX } = await import('gatsby-plugin-mdx');
const remarkGfm = (await import('remark-gfm')).default;

const mdxContent = await compileMDX(
  { absolutePath, source: content.toString() },
  {
    outputFormat: 'function-body',
    jsxRuntime: 'automatic',
    jsx: false,
    useDynamicImport: true,
    remarkPlugins: [remarkGfm]
  }, cache, reporter
);

注意:如果你的gatsby-node.ts使用顶级await,需确保tsconfig.json中compilerOptions.module设置为ESNext或ES2022,并将代码放在异步回调(如createPages)中执行。

3. 可选:全局ESM配置

如果希望项目默认使用ES模块,可在package.json中添加:

{
  "type": "module"
}

但此设置会让所有.js文件默认视为ESM,需确保其他CommonJS代码(如旧插件)兼容。若不想全局设置,可将gatsby-config和gatsby-node改为.mjs扩展名(Gatsby v4+支持)。


内容的提问来源于stack exchange,提问作者Sanjeet A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:40:53