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

Gatsby本地TypeScript插件sourceNodes不执行问题求助

解决Gatsby本地插件TypeScript版gatsby-node.ts不执行sourceNodes的问题

核心问题根源

Gatsby对TypeScript格式的插件文件有特定导出要求,不能直接使用CommonJS的exports语法,必须采用ES模块导出或符合Gatsby TS类型定义的导出方式。

具体修复步骤

  1. 给本地插件配置TypeScript环境
    在本地插件根目录(plugins/source-plugin)创建tsconfig.json,内容如下:

    {
      "compilerOptions": {
        "module": "ESNext",
        "target": "ES2020",
        "moduleResolution": "node",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "strict": true
      },
      "include": ["src/**/*", "gatsby-node.ts"]
    }
    
  2. 修正gatsby-node.ts的导出语法
    放弃CommonJS的exports写法,改用ES模块导出,同时引入Gatsby类型定义确保语法合规:

    import type { GatsbyNode } from "gatsby"
    
    console.log("LOADED AS TS")
    
    export const sourceNodes: GatsbyNode["sourceNodes"] = async ({ actions }) => {
      console.log("sourceNodes executed!")
      // 这里编写你的sourceNodes业务逻辑
    }
    
  3. 补充插件的TypeScript依赖
    在插件目录下执行命令,安装必要的类型依赖:

    npm install --save-dev typescript @types/node @types/gatsby
    
  4. 确认根项目对插件的引用正确
    根项目gatsby-config.ts中要准确指向本地插件路径:

    export default {
      plugins: [
        {
          resolve: "./plugins/source-plugin",
        },
      ],
    }
    

常见错误排查

  • 若出现Expected ',', got 'exports'编译错误,说明混用了CommonJS与ES模块语法,统一改为ES模块的export写法即可。
  • 若仅初始化打印生效、sourceNodes内打印无输出,需检查导出变量名是否严格为sourceNodes,以及类型是否匹配GatsbyNode["sourceNodes"]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:40:58