我创建一个测试项目如下:
src/
test.ts
package.json
tsconfig.json
我安装了ts-node,现在我进行运行项目报错:
npx ts-node src/test.ts
报错:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/Test/react/react-demo-03/src/test.ts
at new NodeError (node:internal/errors:387:5)
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:75:11)
at defaultGetFormat (node:internal/modules/esm/get_format:117:38)
at defaultLoad (node:internal/modules/esm/load:81:20)
at nextLoad (node:internal/modules/esm/loader:163:28)
at ESMLoader.load (node:internal/modules/esm/loader:601:26)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
at new ModuleJob (node:internal/modules/esm/module_job:63:26)
at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:476:17)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
我的tsconfig.json配置如下:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src",
"src/testApp/test.ts"
]
}
请问为何会出现这样的错误呢?
在 tsconfig.json 中添加 "ts-node": { "esm": true } 试试:
参考的是这个文档:
ts-node常见问题