如何在Node.js中运行导入了使用其他模块解析方式转译的模块的JavaScript代码?
我正在使用一个带有npm workspaces的单仓库(monorepo)和ZenStack ORM。代码全部用TypeScript编写。我有一个数据种子应用,打算在ZenStack的 seed阶段运行。
我的所有应用和包都能通过 tsc 正确构建。然而在运行时执行种子命令时遇到困难。它在尝试在某个工作区包中进行本地导入时失败。
结构如下:
├── apps
│ ├── [...]
│ ├── api (node expressjs server)
│ ├── web (vite/vue bundle)
│ ├── data-seeding
├── etc
└── packages
├── [...]
├── lib
└── orm
这些包的tsconfig.json看起来是这样的:
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"declaration": true,
"outDir": "dist",
"esModuleInterop": true
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
以及它们的package.json:
"type": "module",
"exports": {
".": "./dist/index.js"
},
"types": "dist/index.d.ts",
我可以用以下命令构建我的数据种子应用:
"module": "esnext",
"moduleResolution": "bundler",
但不能用:
"module": "nodenext",
"moduleResolution": "nodenext",
因此,在运行主种子脚本时会失败。我尝试了多种方式,使用Node或 tsx,但不确定为何会失败,因此也不知道该如何正确修复。
- 使用
tsx:
``` tsx src/main.ts
Cannot find module '@/zenstack/schema' Require stack: - [...]/packages/orm/dist/dbContext.js - [...]/packages/orm/dist/index.js - [...]/apps/data-seeding/src/main.ts ```
这里的@/zenstack/schema在我的orm包中。
- 使用
node:
``` node dist/main.js
Cannot find module '[...]/apps/data-seeding/dist/seedLogging' imported from [...]/apps/data-seeding/dist/main.js ```
这里的seedLogging在我的data-seeding应用中。
我猜测(也不能完全确定)问题出在Node或 tsx无法轻易解析模块路径,因为它们在不同的module/moduleResolution下被转译。
解决方案
使用bun取代node就是正确的选择。
一切开箱即用,就像任何工具应该做到的那样。