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

TypeScript编译后模块导入路径未正确转为.js后缀问题

解决NodeNext模式下TypeScript导入后缀未自动转换为.js的问题

问题根源

当前tsconfig.json缺少与module: NodeNext匹配的模块解析配置,且未明确项目的ES模块类型,导致TypeScript编译时未将导入的.ts后缀替换为.js。

修复步骤

1. 更新package.json

在项目根目录的package.json中添加"type": "module",明确项目采用ES模块规范:

{
  "type": "module",
  // 其他原有配置项...
}

2. 修改tsconfig.json

补充模块解析配置,并确保编译目标支持ES模块:

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext", // 必须与module值保持一致
    "target": "ES2020", // 确保编译后代码兼容Node.js的ES模块
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "dist",
    "allowImportingTsExtensions": true
  },
  "include": ["src/**/*"] // 明确指定需要编译的文件范围
}

3. 修正导入路径(关键)

根据你的项目结构,src/index.ts与src/library.ts处于同一目录,当前导入路径../library.ts存在错误,应改为:

import { someFunc } from './library.ts';

替代方案(无需写.ts后缀)

如果不想在导入时添加.ts后缀,可以关闭allowImportingTsExtensions,导入时直接写模块名:

// index.ts
import { someFunc } from './library';

编译后会自动转换为:

// dist/index.js
import { someFunc } from './library.js';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 01:41:20