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

运行ts-node-dev启动Express服务时出现ES Module加载错误求助

问题描述

执行命令npx ts-node-dev --respawn --transpile-only index.ts启动Express服务时,出现编译错误:

rob@hi~/dev/robrendellwebsite$ npx ts-node-dev --respawn --transpile-only index.ts
[INFO] 06:23:55 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.9.1, typescript ver. 4.8.4)
Compilation error in /home/rob/dev/robrendellwebsite/index.ts
Error: Must use import to load ES Module: /home/rob/dev/robrendellwebsite/index.ts
    at Object.<anonymous> (/home/rob/dev/robrendellwebsite/index.ts:1:7)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._compile (/home/rob/dev/robrendellwebsite/node_modules/source-map-support/source-map-support.js:568:25)
    at Module.m._compile (/tmp/ts-node-dev-hook-6490566241511986.js:69:33)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-6490566241511986.js:114:20)
    at require.extensions.<computed> (/tmp/ts-node-dev-hook-6490566241511986.js:71:20)
    at Object.nodeDevHook [as .ts] (/home/rob/dev/robrendellwebsite/node_modules/ts-node-dev/lib/hook.js:63:13)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Function.Module._load (node:internal/modules/cjs/loader:878:12)
[ERROR] 06:23:55 Error: Must use import to load ES Module: /home/rob/dev/robrendellwebsite/index.ts

已尝试操作

在package.json中添加了"type":"module"配置,但问题仍未解决。


解决方案

你已经在package.json里设置了"type": "module",说明项目采用ES模块规范,但ts-node-dev默认按CommonJS模式处理文件,导致模块加载冲突。按以下步骤调整:

1. 配置tsconfig.json

确保tsconfig.json包含这些关键配置:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*", "index.ts"],
  "exclude": ["node_modules"]
}
  • module: "ESNext":指定编译输出为ES模块格式
  • moduleResolution: "NodeNext":和Node.js的模块解析逻辑对齐,适配ES模块加载规则

2. 修改启动命令

更新package.json里的dev脚本,添加--esm参数:

"dev": "ts-node-dev --respawn --pretty --transpile-only --esm index.ts"

--esm参数会强制ts-node-dev以ES模块模式加载文件,匹配项目的"type": "module"设置。

3. 测试启动

运行更新后的命令:

npm run dev

此时应该能正常编译并启动Express服务。

如果仍有问题,检查项目依赖是否存在仅支持CommonJS的老版本包,尝试升级到支持ES模块的版本即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:35:25