Windows运行Node.js TypeScript项目报错ERR_UNKNOWN_FILE_EXTENSION
问题描述
代码在UNIX系统运行正常,但Windows系统执行启动命令nodemon index.ts --no-warnings时报错,错误信息如下:
[nodemon] starting `ts-node index.ts --no-warnings` TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\{MY_PROJECT_PATH}\server\index.ts
涉及的配置文件如下:
tsconfig.json
{ "compilerOptions": { "module": "ES2022", "strict": true, "moduleResolution": "Node", "noImplicitAny": true, "sourceMap": true, "allowSyntheticDefaultImports": true }, "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"], "ts-node": { "esm": true, "compilerOptions": { "module": "CommonJS" } } }
package.json
{ "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "", "start": "nodemon index.ts --no-warnings" }, "author": "", "license": "ISC", "dependencies": {} }
解决方案
通过以下调整可解决Windows下的报错问题:
修正
tsconfig.json的include路径
当前include仅覆盖src目录下的文件,但入口文件index.ts在项目根目录,导致ts-node无法识别该文件。修改为:"include": ["index.ts", "src/**/*"]统一模块系统配置
tsconfig.json中ts-node段同时开启esm: true和module: "CommonJS"会引发模块系统冲突,建议统一为CommonJS(更兼容Windows和nodemon环境):"ts-node": { "esm": false, "compilerOptions": { "module": "CommonJS" } }同时将根级
compilerOptions的module也设为CommonJS,避免配置不一致:"compilerOptions": { "module": "CommonJS", // 其余配置保持不变 }更新启动脚本
在nodemon命令中明确指定用ts-node执行,避免Windows下的命令解析异常:"scripts": { "start": "nodemon --exec ts-node index.ts --no-warnings" }安装必要依赖
确保已安装核心开发依赖:npm install -D ts-node typescript nodemon
内容的提问来源于stack exchange,提问作者Nandini
相关产品推荐
相关产品推荐

