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

TypeScript导入失败:运行node dao.ts报Cannot use import statement outside a module错误

报错解决方案

这个报错是因为Node.js默认使用CommonJS模块规范,同时无法直接解析TypeScript语法,有以下三种常用解决路径:

方案1:使用CommonJS模块规范(无需修改项目全局配置)

  • 修改项目tsconfig.json的compilerOptions配置项,指定模块编译规则为CommonJS:
{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ESNext",
    // 其余原有配置保持不变即可
  }
}
  • 执行tsc dao.ts编译TypeScript文件为JS文件,再执行node dao.js即可正常运行。

方案2:使用ES模块规范

  • 先在项目package.json中添加配置,声明项目使用ES模块规范:
{
  "type": "module",
  // 其余原有配置保持不变即可
}
  • 修改tsconfig.json的compilerOptions配置:
{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    // 其余原有配置保持不变即可
  }
}
  • 执行tsc dao.ts编译后,运行node dao.js即可。

方案3:直接运行TS文件(无需手动编译)

安装ts-node工具实现边转译边执行:

  • 安装依赖:npm install -D ts-node typescript @types/node
  • 如果使用CommonJS规范,直接执行命令:npx ts-node dao.ts
  • 如果使用ES模块规范,执行命令:npx ts-node --esm dao.ts

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:06:00