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

Node.js+Express+TypeScript配置报错:未知文件扩展名.ts

解决Node.js+Express+TypeScript项目中".ts"文件扩展名未知错误的正确配置

出现TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"错误的核心原因是:你在package.json中设置了"type": "module"(启用ES模块规范),但默认的ts-node配置仅支持CommonJS模块,两者的模块处理逻辑冲突导致无法识别.ts文件。

以下是完整的修正配置方案:

1. 调整tsconfig.json配置

补充ES模块适配选项,并添加ts-node的ES模块支持配置:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "baseUrl": "src",
    "outDir": "dist",
    "sourceMap": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  }
}
  • target: 指定编译后的JS版本,匹配Node.js的ES模块支持能力
  • resolveJsonModule: 允许项目中导入JSON文件
  • skipLibCheck: 跳过第三方类型库的检查,避免类型冲突
  • ts-node配置块:显式开启ES模块支持,指定使用Node.js的解析规则

2. 修改package.json配置

调整入口文件、脚本命令,适配ES模块和项目结构:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "dist/index.js",
  "scripts": {
    "dev": "nodemon --exec ts-node src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.18.2",
    "mongoose": "^7.5.0"
  },
  "devDependencies": {
    "@types/express": "^4.17.17",
    "@types/node": "^20.5.7",
    "nodemon": "^3.0.1",
    "ts-node": "^10.9.1",
    "typescript": "^5.2.2"
  }
}
  • main: 指定编译后的生产环境入口文件
  • scripts:
    • dev: 开发环境使用nodemon监听文件变化,通过ts-node直接运行src下的index.ts
    • build: 调用tsc编译TypeScript代码到dist目录
    • start: 生产环境运行编译后的JS文件

3. 验证运行

  1. 执行npm run build,确认dist目录生成编译后的JS文件
  2. 执行npm run dev,启动开发服务器,验证错误消失,服务正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:06:29