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.tsbuild: 调用tsc编译TypeScript代码到dist目录start: 生产环境运行编译后的JS文件
3. 验证运行
- 执行
npm run build,确认dist目录生成编译后的JS文件 - 执行
npm run dev,启动开发服务器,验证错误消失,服务正常运行
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

