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

使用ts-node运行TypeScript项目时引入外部文件报错:找不到模块

解决ts-node/tsc运行TypeScript时"Cannot find module"错误

问题原因

  1. 导入路径错误:index.ts 本身就在 src 目录下,却使用了 ../src/domain/database 这种向上跳转再回退到src的路径,导致模块解析器无法定位到正确文件。
  2. ESM模块配置不兼容:package.json 中设置了 "type":"module",但 tsconfig.json 的模块解析规则未完全适配ESM模式,引发ts-node和tsc的解析冲突。

解决步骤

1. 修正导入路径

将 index.ts 中的导入语句改为相对当前文件的正确路径:

// index.ts
// 替换原错误导入路径
import database from './domain/database';

2. 调整tsconfig.json配置

适配ESM模式的模块解析规则,更新配置如下:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "esnext",
    "moduleResolution": "bundler", // 替换为bundler,匹配Node.js ESM解析逻辑
    "esModuleInterop": true,
    "outDir": "./dist",
    "skipLibCheck": true,
    "strict": false // 根据项目需求可选开启
  },
  "include": ["src/**/*"], // 明确指定编译文件范围
  "exclude": ["node_modules"]
}

3. 优化运行脚本

为ts-node添加ESM兼容参数,同时完善构建后的运行逻辑:

"dev": "ts-node --esm --experimental-specifier-resolution=node src/index.ts",
"build": "tsc && node dist/index.js"

验证修复

  • 执行 npm run dev 测试开发模式是否正常启动
  • 执行 npm run build 后,运行 node dist/index.js 确认生产构建可正常运行

内容的提问来源于stack exchange,提问作者Michael-Liendo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:52:45