我正在尝试使用Lerna设置基于TypeScript的monorepo,其中有两个软件包 bar 和 foo 。 foo 通过路径别名导入 bar ,但操作失败。
tree
.
├── lerna.json
├── package.json
├── package-lock.json
├── packages
│ ├── bar
│ │ ├── lib
│ │ │ ├── index.d.ts
│ │ │ └── index.js
│ │ ├── package.json
│ │ ├── src
│ │ │ └── index.ts
│ │ ├── tsconfig.build.json
│ │ └── tsconfig.json
│ └── foo
│ ├── lib
│ │ ├── index.d.ts
│ │ └── index.js
│ ├── package.json
│ ├── src
│ │ └── index.ts
│ ├── tsconfig.build.json
│ └── tsconfig.json
├── tsconfig.build.json
└── tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true
}
}
{
"extends": "./tsconfig.build.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@company/bar": [
"packages/bar"
],
"@company/foo": [
"packages/foo"
]
}
}
}
{
"packages": [
"packages/*"
],
"version": "0.0.0"
}
{
"name": "root",
"private": true,
"scripts": {
"tsc": "lerna run tsc"
},
"devDependencies": {
"lerna": "^3.22.1",
"ts-node": "^9.0.0",
"ts-node-dev": "^1.0.0-pre.63",
"typescript": "^4.0.3"
}
}
包装 bar :
export const bar = 'bar';
{
"name": "@company/bar",
"version": "1.0.0",
...
"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
"tsc": "tsc -p tsconfig.build.json"
}
}
{
"extends": "../../tsconfig.build.json",
"compilerOptions": {
"outDir": "./lib"
},
"include": [
"src/**/*"
]
}
{
"extends": "../../tsconfig.json"
}
软件包 foo :
import { bar } from '@company/bar';
console.log(bar);
{
"name": "@company/foo",
"version": "1.0.0",
...
"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
"tsc": "tsc -p tsconfig.build.json"
}
}
{
"extends": "../../tsconfig.build.json",
"compilerOptions": {
"outDir": "./lib"
},
"include": [
"src/**/*"
]
}
{
"extends": "../../tsconfig.json"
}
最后:
运行npm run tsc
编译我的包,其中 foo 导入 bar 。它给了我以下错误:
> lerna run tsc
lerna notice cli v3.22.1
lerna info Executing command in 2 packages: "npm run tsc"
lerna info run Ran npm script 'tsc' in '@company/bar' in 2.4s:
> @company/bar@1.0.0 tsc /.../monorepo-lerna/packages/bar
> tsc -p tsconfig.build.json
lerna ERR! npm run tsc exited 2 in '@company/foo'
lerna ERR! npm run tsc stdout:
> @company/foo@1.0.0 tsc /.../monorepo-lerna/packages/foo
> tsc -p tsconfig.build.json
src/index.ts(1,21): error TS2307: Cannot find module '@company/bar' or its corresponding type declarations.
该错误本身非常清楚,尽管我不知道如何解决它(./tsconfig.json(3)中的路径别名看起来不错)。有什么想法我的配置搞砸了吗?我想念什么?
如果我将import { bar } from '@company/bar';
更改为import { bar } from '../../bar/src';
,则一切正常,但是我想坚持第一种导入bar
的方法。
答案 0 :(得分:1)
这是允许您将软件包作为@company/bar
"paths": {
"@company/bar": [
"packages/bar"
],
"@company/foo": [
"packages/foo"
]
}
这是在./tsconfig.json
中指定的。当您尝试编译软件包foo
时,它使用的是./packages/foo/tsconfig.build.json
,它从不包含根配置或不指定路径本身,您可能想从基础tscofig
中删除导入方案并添加它们到内部软件包配置:
./packages/foo/tsconfig.build.json
应该包含以下内容:
{
"compilerOptions": {
"paths": {
"@company/bar": [
"../bar"
]
}
}
}
并且类似地,packages/bar/tsconfig.build.json
应该被允许导入@company/foo
。