无法运行 TS 节点 + ES 应用程序 - 获取"ERR_UNKNOWN_FILE_EXTENSION"或"新ERR_MODULE_NOT_FOUND"



我正试图将我的代码编译为ES代码(在package.json中使用"type": "module",在tsconfig.json内使用"module": "esnext")。

我无法使用以下3种方法中的任何一种运行它:

  1. ts-node src/server.ts导致:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/src/server.ts
at new NodeError (node:internal/errors:363: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 Loader.import (node:internal/modules/esm/loader:177:17)
at Object.loadESM (node:internal/process/esm_loader:68:5)

从这个线程来看,ts节点似乎有问题。

  1. 所以我尝试node --loader ts-node/esm ./src/server.ts并得到:
(node:45543) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/dist-raw/node-esm-resolve-implementation.js:383
throw new ERR_MODULE_NOT_FOUND(
^
CustomError: Cannot find module '/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/src/app' imported from /Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/src/server.ts
at finalizeResolution (/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/dist-raw/node-esm-resolve-implementation.js:383:11)
at moduleResolve (/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/dist-raw/node-esm-resolve-implementation.js:818:10)
at Object.defaultResolve (/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/dist-raw/node-esm-resolve-implementation.js:929:11)
at /Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/src/esm.ts:68:38
at Generator.next (<anonymous>)
at /Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/dist/esm.js:8:71
at new Promise (<anonymous>)
at __awaiter (/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/dist/esm.js:4:12)
at resolve (/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/node_modules/ts-node/dist/esm.js:32:16)
at Loader.resolve (node:internal/modules/esm/loader:89:40)

但是src/app.ts显然就在文件夹里!

  1. 所以我尝试先用tsc编译,然后运行node --loader ts-node/esm ./dist/src/server.js。我得到了与(2)几乎相同的错误,只是这次缺少了/Users/ilmoi/Dropbox/crypto_bc/dbricks/mvp/server/dist/src/app。这也没有任何意义,因为我可以在文件夹中看到它

如何解决此问题?我已经阅读了堆栈溢出的每个线程,我没有选择了。为什么运行ES节点应用程序如此困难?

我遇到了这个问题,我想把所有文件都保存在typescript中。我看到了@BlueFrog提供的答案,但我没有将模块导入转换为.js,而是使用了这个实验标志:

node --experimental-specifier-resolution=node --loader ts-node/esm myScript.ts

它工作成功。

更多信息点击这里

遇到了相同的问题。通过以下ts节点问题进行修复。


TL;DR只需将.js扩展添加到模块导入中,并使用node --loader ts-node/esm src/index.ts运行ts节点

相关内容

  • 没有找到相关文章

最新更新