TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for xx.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"
假如你在编写一个 Typescript 库函数,你希望将其编译为 ESModule ,那么你可以通过在 package.json 中声明 "type": "module" 来告诉使用者你的库函数使用的模块规范是 ESModule 。
但如果你使用 ts-node 来运行这个库时,你很可能会遇到一行错误:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"
这是因为通过 tsc --init 生成默认 tsconfig.json 使用的默认模块规范是:"module": "commonjs", 也就是说 Typescript 的默认配置是将代码编译为 commonjs 的模块,而非我们在 package.json 中声明的 module (即 ES module)模块。
ts-node 在运行时会既会读取 package.json 又会读取 tsconfig.json ,而二者的配置相互冲突,于是产生了错误。
那怎么办呢?不用慌, ts-node 的 README.md 文件中已经给出了解决办法:
{
"compilerOptions": {
"module": "ESNext" // or ES2015, ES2020
},
"ts-node": {
// Tell ts-node CLI to install the --loader automatically, explained below
"esm": true
}
}
非常好理解,既然 package.json 和 tsconfig.json 的配置相互冲突,那么让他们一致声明模块为 ESModule 不就好了吗? esm 配置表示在调用 ts-node 时自动添加 ts-node --esm 参数。
因此上面做的事情总结为:
- 对 Typescript 声明编译目标为 ESModule
- 对 ts-node 声明运行方法为
ts-node --esm,将项目看作 ES-Module 模块。
注意
如果你在添加了上述配置后依然报相同的错误,是因为 Nodejs 支持 ES-Module 依然是一个实验性的功能,不稳定, 可见 ECMAScript Modules in Node.js中的一段话:
For the last few years, Node.js has been working to support running ECMAScript modules (ESM). This has been a very difficult feature to support, since the foundation of the Node.js ecosystem is built on a different module system called CommonJS (CJS).
翻译成人话就是:Node.js 底层生态都是用 CommonJS 规范写的,要支持 ESModule 改起来太TM难了。
因此有可能是 Nodejs 的新版本对相关的 API 做了调整, ts-node 还没有来得及进行适配,笔者将 Nodejs 版本从 v20.5.1 降到 v18.17.1 后不再出现错误。

浙公网安备 33010602011771号