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

NodeJS v18+TS4.8.4项目无法导入JSON文件的问题求助

NodeJS v18 + TS4.8.4 JSON导入问题及模块切换后的扩展名报错修复

方案一:保持CommonJS模块,修复JSON导入失败问题

若不想切换模块系统,可按以下配置调整:

  • 显式设置moduleResolution为node(CommonJS模式下默认值,但显式声明可避免解析歧义),同时确保resolveJsonModule和allowSyntheticDefaultImports开启(后者用于支持默认导入JSON):
"compilerOptions": {
  "esModuleInterop": true,
  "target": "esnext",
  "lib": ["esnext"],
  "module": "commonjs",
  "moduleResolution": "node",
  "resolveJsonModule": true,
  "allowSyntheticDefaultImports": true,
  "forceConsistentCasingInFileNames": true,
  "strict": true,
  "skipLibCheck": true
}
  • 检查include配置,确保config.json所在路径被纳入TS编译范围:
"include": ["src/**/*", "../config.json"] // 根据实际路径调整
  • 若路径无误仍报错,可手动创建JSON类型声明文件config.json.d.ts:
declare module '../config.json' {
  const content: {
    // 按JSON实际结构定义类型,例如:
    apiUrl: string;
    port: number;
  };
  export default content;
}

方案二:切换到NodeNext/ES模块,修复相对导入扩展名报错

若保留module: "nodenext",需适配ES模块的导入规范:

  • 在项目根目录package.json中添加"type": "module",明确项目使用ES模块:
{
  "type": "module"
}
  • 调整所有相对导入语句,为TS文件的导入添加.js扩展名(TS编译后生成.js文件,Node.js会按此路径查找):
    错误写法:import MyClass from './myclass';
    修改为:import MyClass from './myclass.js';
  • 若不想逐个修改导入语句,可在tsconfig.json中添加moduleSuffixes,让TS自动匹配扩展名:
"compilerOptions": {
  // 原有配置不变
  "moduleSuffixes": [".ts", ".js"]
}
  • 调整target为NodeJS v18兼容的版本,建议设置为ES2020或更高:
"target": "ES2020"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:31:13