Skip to main content

ts-node

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

相关issues

错误信息

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for D:\CPS\MyProject\demo\cps-cli\cps-cli-template-node-ts\src\index.ts
at new NodeError (node:internal/errors:371:5)
at Loader.defaultGetFormat [as _getFormat] (node:internal/modules/esm/get_format:71:15)
at Loader.getFormat (node:internal/modules/esm/loader:105:42)
at Loader.getModuleJob (node:internal/modules/esm/loader:243:31)
at async Loader.import (node:internal/modules/esm/loader:177:17)
at async Object.loadESM (node:internal/process/esm_loader:68:5)
at async handleMainPromise (node:internal/modules/run_main:63:12) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

解决办法

1、采用ESM

  • package.json type字段为 module
  • ts-node>=10.7 使用ts-node --esm $file来执行文件,ts-node采用原生esm模式执行文件
  • ts-node<=10.7 使用node --loader ts-node/esm $filenode --loader ts-node/esm $file
// package.json
{
"type": "module",
}
// tsconfig.json
{
"ts-node": {
"compilerOptions": {
"module": "ESNext",
"types": ["node"]
}
}
}

2、采用CommonJS

  • package.json 确保没有添加type字段,或者type字段为 CommonJS
  • tsconfig.json 内的 ts-node 指定module 字段输出为 CommonJS
// tsconfig.json
{
"ts-node": {
"compilerOptions": {
"module": "CommonJS", // 此处同时必须指定commonJS
"types": ["node"]
}
}
}

Unknown or unexpected option: --esm

原因分析

旧版用了新特性

旧版的 ts-node 没有 --esm flag,更新 ts-node 到10.7.0以上后才支持改flag

旧版 ts-node 可以使用 以下方式替代 --esmflag

  • node --loader ts-node/esm $file
  • node --loader ts-node/esm $file
Error: Unknown or unexpected option: --esm
at arg (w:\CPS\nodejs\v16.6.2\node_modules\ts-node\node_modules\arg\index.js:88:19)
at main (w:\CPS\nodejs\v16.6.2\node_modules\ts-node\dist\bin.js:18:67)
at Object.<anonymous> (w:\CPS\nodejs\v16.6.2\node_modules\ts-node\dist\bin.js:350:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47 {
code: 'ARG_UNKNOWN_OPTION'
}