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

升级Node.js 20 LTS+ESM后,VS Code调试TS Express应用报错

解决Node.js 20 ESM模式下调试TypeScript Express应用的「Unknown file extension .ts」错误

问题核心

切换到Node.js 20 ESM模式后,Node默认无法识别.ts扩展名,且ts-node的ESM模式需要明确配置,单纯添加--esm参数不足以让nodemon、ts-node和VS Code调试器协同工作。

分步解决方案

1. 确认项目ESM基础配置

  • 在package.json中启用ESM:
    {
      "type": "module"
    }
    
  • 调整tsconfig.json编译选项适配ESM:
    {
      "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "Bundler",
        "target": "ES2020", // 匹配Node.js 20支持的语法版本
        "outDir": "./dist",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "strict": true
      },
      "include": ["src/**/*"]
    }
    

2. 配置nodemon支持ESM+TypeScript

在项目根目录创建nodemon.json,指定用ts-node的ESM模式执行代码:

{
  "watch": ["src"],
  "ext": "ts,js",
  "exec": "ts-node --esm ./src/index.ts" // 替换为你的实际入口文件路径
}

3. 修正VS Code launch.json配置

调整调试配置,让nodemon正确加载ESM配置并调用ts-node:

{
    "type": "node",
    "request": "launch",
    "name": "TypeScript Node",
    "skipFiles": [
        "<node_internals>/**"
    ],
    "runtimeExecutable": "nodemon",
    "internalConsoleOptions": "neverOpen",
    "console": "integratedTerminal",
    "runtimeArgs": ["--config", "nodemon.json"],
    "program": "${workspaceFolder}/src/index.ts", // 明确入口文件路径
    "env": {
        "NODE_ENV": "development"
    }
}

4. 额外检查项

  • ESM模式下所有导入语句必须使用完整扩展名(比如import router from './router.ts')
  • 确保ts-node版本(当前10.9.2)与Node.js 20兼容,必要时可升级到最新稳定版

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 10:12:14