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

Node.js ≥20 + TypeScript 5下.ts扩展名未知错误求助

解决TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" 问题

当前使用Node.js版本≥20、TypeScript 5,package.json与tsconfig.json配置如下,但运行时仍触发错误:TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts",尝试过常见方案仍无法解决。

package.json 配置

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.ts",
   "type": "module",
  "scripts": {
    "build":"tsc",
    "dev": "nodemon"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "mongoose": "^8.4.1"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/express": "^4.17.21",
    "@types/node": "^20.14.2",
    "nodemon": "^3.1.3",
    "ts-node": "^10.9.2",
    "typescript": "^5.4.5"
  }
}

tsconfig.json 配置

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "experimentalDecorators": true,
    "rootDir": "./src",
    "outDir": "./build",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "importHelpers": true
   
  },
  "ts-node": {
    "esm": true
},
"lib": ["esnext"],
  "include": ["src"]
}

可行解决方案

  • 修改dev脚本,明确让nodemon使用ts-node执行TS文件:
    将package.json中的"dev": "nodemon"改为:
    "dev": "nodemon --exec ts-node ./src/index.ts"
    
  • 完善ts-node的ES模块解析配置,在tsconfig.json的ts-node字段中添加:
    "ts-node": {
      "esm": true,
      "experimentalSpecifierResolution": "node"
    }
    
  • 调整main字段指向生产环境的编译产物,避免生产环境加载TS文件:
    将package.json中的"main": "./src/index.ts"改为:
    "main": "./build/index.js"
    
  • 若仍有问题,尝试升级ts-node到最新兼容版本,执行命令:
    npm install ts-node@latest --save-dev
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:35:09