我们有一个这样的代码库设置:
-A
--utils
---index.ts
--index.ts
--tsconfig.json
-B
--utils
---index.ts
--index.ts
--tsconfig.json
-tsconfig.json
我们的根tsconfig.json
包含以下内容: "paths": {
"A/*": ["A/*"],
"B/*": ["B/*"],
},
每个包裹的tsconfig.json
包含以下内容: "paths": {
"utils/*": ["./utils/*"],
},
这适用于我们当前的目的,因为我们目前只使用 TS 进行类型检查,但我们实际上使用 Babel 生成构建,它在 alias
中有类似的设置各种属性.babelrc
文件。我们希望使用
ts-node
开始运行代码(或等价物)并且遇到了在运行时,TS 不知道如何解析模块的问题。例如:// A/index.ts
import { someUtil } from 'utils'
export const someFunc() => someUtil();
// B/index.ts
import { someFunc } from 'A';
当我们运行 npx ts-node ./B/index.ts
我们收到一条错误消息,提示“找不到模块 'utils'。我们知道我们可以通过将所有内容提升到根
tsconfig.json
来完成此工作。 ,但必须 import { someUtil } from 'A/utils
似乎是多余的当您已经在包 A 中时。有没有办法以我们的方式使用路径?我们还阅读了一些关于项目引用的内容并尝试过,但它似乎并没有让我们走到任何地方。
最佳答案
里面tsconfig.json
在每个项目中你应该使用的文件extends
在根上 tsconfig
像这样:
// A/tsconfig.json
{
"extends": "../tsconfig.json",
...
}
以这种方式,所有子项目都将继承其他通用包的路径。我认为您甚至可以定义
utils
根上的路径,这样你也不必重复。更多关于
extends
这里的选项:https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#tsconfig-bases
更新
你还需要使用这个库:
https://www.npmjs.com/package/tsconfig-paths
在
package.json
内在 ts-node
scripts
中的脚本您使用的属性(property):ts-node ... -r tsconfig-paths/register ... index.ts
.该库将读取
ts-config.json
中的包并将它们放入node_modules
,因此当您使用 node 或 ts-node 运行时,您的其他包可以找到它们。
关于typescript - 如何协调 monorepo 与多个 tsconfig.json,每个 tsconfig.json 都有自己的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66790078/