Gatsby本地TypeScript插件sourceNodes不执行问题求助
解决Gatsby本地插件TypeScript版
gatsby-node.ts不执行sourceNodes的问题 核心问题根源
Gatsby对TypeScript格式的插件文件有特定导出要求,不能直接使用CommonJS的exports语法,必须采用ES模块导出或符合Gatsby TS类型定义的导出方式。
具体修复步骤
给本地插件配置TypeScript环境
在本地插件根目录(plugins/source-plugin)创建tsconfig.json,内容如下:{ "compilerOptions": { "module": "ESNext", "target": "ES2020", "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": true, "strict": true }, "include": ["src/**/*", "gatsby-node.ts"] }修正
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业务逻辑 }补充插件的TypeScript依赖
在插件目录下执行命令,安装必要的类型依赖:npm install --save-dev typescript @types/node @types/gatsby确认根项目对插件的引用正确
根项目gatsby-config.ts中要准确指向本地插件路径:export default { plugins: [ { resolve: "./plugins/source-plugin", }, ], }
常见错误排查
- 若出现
Expected ',', got 'exports'编译错误,说明混用了CommonJS与ES模块语法,统一改为ES模块的export写法即可。 - 若仅初始化打印生效、
sourceNodes内打印无输出,需检查导出变量名是否严格为sourceNodes,以及类型是否匹配GatsbyNode["sourceNodes"]。
内容的提问来源于stack exchange,提问作者user3193620
相关产品推荐
相关产品推荐

