node.js - Node js 在尝试运行 npm start 时提示未知的文件扩展名 .ts
我用 Express 在 js 中写了一个小的服务器脚本,但后来改变主意想把它转换成 ts,所以我做了,但从那以后,每次我尝试运行 npm start,node 都会发给我一个错误信息,说未知的文件扩展名 .ts
这是错误:
PS C:\Users\aryan\OneDrive\Documents\GitHub\spacious-forms> npm start
> [email start
> npx ts-node --esm src/server.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\aryan\OneDrive\Documents\GitHub\spacious-forms\src\server.ts
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
at defaultLoad (node:internal/modules/esm/load:141:22)
at async nextLoad (node:internal/modules/esm/hooks:749:22)
at async nextLoad (node:internal/modules/esm/hooks:749:22)
at async Hooks.load (node:internal/modules/esm/hooks:382:20)
at async MessagePort.handleMessage (node:internal/modules/esm/worker:199:18) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
这是我的 package.json 文件
{
"name": "spacious-forms",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"start": "npx ts-node --esm src/server.ts",
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.3.8"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/md5": "^2.3.5",
"@types/node": "^20.10.0",
"@vitejs/plugin-vue": "^4.5.0",
"express": "^4.18.2",
"md5": "^2.3.0",
"sqlite3": "^5.1.6",
"tailwindcss": "^3.3.5",
"ts-node": "^10.9.1",
"typescript": "^5.3.2",
"vite": "^5.0.0",
"vue-tsc": "^1.8.22"
}
}
这是我的 tsconfig.json
{
"compilerOptions": {
"esModuleInterop": true,
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"paths": {
"@/*": [
"./*"
]
},
/* Bundler mode */
"moduleResolution": "node",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"ts-node": {
"esm":true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "../src/vite-env.d.ts", "../src/main.ts", "vue.d.ts", "vue.d.ts"],
"references": [{ "path": "./tsconfig.node.json" }]
}
我已经上网搜索并尝试了所有解决方法,包括更改 ES 版本、使用 ts-node 等,但都无效
编辑:
我确实将 'tsconfig.json' 中的 moduleResolution 的 "node" 改为 "Node",但是我得到的错误仍然一样
答案#1
显然,问题出在 ts-node。我用它总是无法正常工作,所以我改用了 tsx,这解决了问题,现在服务器运行没有任何问题。
尝试
npm i -g tsxnpx tsx src/server.js那解决了我的问题
答案#2
如果你正在使用 Node v20,请将此添加到你的 ts.config 文件中
{
"compilerOptions": {
//..
},
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node",
},
}然后运行 node --experimental-loader --loader ts-node/esm src/app.ts 这样做可以解决问题,但会消耗大量 CPU。我更倾向于将 Node 降级到 18.x 版本(我更倾向于 v18.17.1),直到在 Node v20 上解决此问题。
