使用ts-node运行TypeScript代码时报错:Unknown file extension ".ts"
解决ts-node运行.ts文件提示ERR_UNKNOWN_FILE_EXTENSION的问题
可能的原因及对应解决方案
1. 项目启用了ESM模块模式
如果项目根目录的package.json中设置了"type": "module",Node.js会默认以ESM模式处理文件,而ts-node默认适配CommonJS,此时需要显式指定ESM模式运行:
ts-node --esm index.ts
2. 切换为CommonJS模块模式
若无需ESM模式,可修改package.json,移除"type": "module"字段,或者将其改为:
"type": "commonjs"
修改后直接运行原命令即可:
ts-node index.ts
3. 通过tsconfig.json指定编译配置
在项目根目录创建tsconfig.json文件,配置编译选项为CommonJS:
{ "compilerOptions": { "module": "CommonJS", "target": "ES6", "strict": true } }
完成配置后运行ts-node index.ts即可。
4. 使用npx规避全局版本冲突
如果全局安装的ts-node与本地依赖版本不兼容,可使用npx直接调用项目本地的ts-node版本:
npx ts-node index.ts
内容的提问来源于stack exchange,提问作者Anish Pradhan
相关产品推荐
相关产品推荐

