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

如何解决NodeJS编译时第三方包CJS与ESM混合的TS1479错误

解决GraphQL-Yoga编译时TS1479错误

我正在开发基于Node.js的后端应用,使用GraphQL和graphql-yoga框架。应用通过tsx运行正常,但编译时,@graphql-yoga/subscription下多个.d.cts文件出现TS1479错误:当前CommonJS模块的import会生成require调用,但被导入的@repeaterjs/repeater是ECMAScript模块,无法用require导入,建议改用动态import。请问是否可通过调整编译选项解决?

附当前tsconfig.json配置:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "isolatedModules": true,
    "module": "Node16",
    "moduleResolution": "Node16",
    "allowSyntheticDefaultImports" : true,
    "useUnknownInCatchVariables": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2020"
  },
  "type": "module",
  "compileOnSave": true,
  "paths": {},
  "include": [
    "./src/**/*.ts",
    "./src/**/*.d.ts",
    "./test/**/*.ts",
    "./test/**/*.d.ts",
    "index.ts",
    "./.eslintrc.js",
    "./jest.config.js"
  ]
}

可以通过调整TypeScript编译选项解决这个问题,以下是几种可行方案:

方案一:切换模块解析模式为NodeNext

将compilerOptions中的module和moduleResolution从Node16改为NodeNext,该模式对ES模块与CommonJS模块的交叉兼容处理更灵活,能自动适配不同模块类型的导入逻辑:

"compilerOptions": {
  // 保留原有其他配置
  "module": "NodeNext",
  "moduleResolution": "NodeNext"
}

方案二:补充ES模块兼容编译选项

若坚持使用Node16模式,可添加allowImportingTsExtensions并启用resolveJsonModule,增强ES模块的导入兼容性:

"compilerOptions": {
  // 保留原有其他配置
  "allowImportingTsExtensions": true,
  "resolveJsonModule": true
}

方案三:排除第三方类型文件编译检查

如果前两种方案无效,可以在tsconfig.json中添加exclude字段,跳过@graphql-yoga/subscription下的.d.cts文件检查,避免第三方模块的类型兼容性问题影响自身编译:

"exclude": [
  "./node_modules/@graphql-yoga/subscription/**/*.d.cts"
]

注意:排除第三方类型文件可能会丢失部分类型提示,建议优先尝试前两种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:07:21