首页 前端知识 ts-node 报错 ERR_UNKNOWN_FILE_EXTENSION

ts-node 报错 ERR_UNKNOWN_FILE_EXTENSION

2024-04-30 12:04:25 前端知识 前端哥 228 148 我要收藏

发生背景

项目里想用 ts-node 跑个脚本,执行:

$ npm install -g ts-node
$ ts-node ./scripts/html-gen.ts

代码是 TypeScript + ES Module (真香),于是 ts-node 开始抱怨:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for ...\scripts\html-gen.ts
    at new NodeError (node:internal/errors:399:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121: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:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:64:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

解决方案

tsconfig.json 中添加 "ts-node": { "esm": true } 即可。

@@ -4,5 +4,8 @@
     "outDir": "dist",
     "isolatedModules": true
   },
-  "include": ["src/**/*.ts", "components/**/*.vue", "scripts/*.ts"]
+  "include": ["src/**/*.ts", "components/**/*.vue", "scripts/*.ts"],
+  "ts-node": {
+    "esm": true
+  }
 }

(如果还报错,请参考这篇文章)

发生原因

ts-node 默认将文件视为 CommonJS ,需要显式声明为 ES Module 。(个人理解)

参考资料

  • Troubleshooting | ts-node
转载请注明出处或者链接地址:https://www.qianduange.cn//article/6725.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!