問題描述
如何使用 Yarn 工作區將共享依賴項添加到 monorepo? (How do I add shared dependencies to a monorepo using Yarn workspaces?)
我正在使用 Yarn 的 Workspaces 功能來管理 monorepo。一些單獨的工作區在他們自己的 package.json
中定義了自己的依賴項,但是我也有一些共享依賴項(一些用於測試整個 repo,一些用於所有工作區)。如何以正確的方式聲明這些?
如果我嘗試將它們添加到根 package.json
,Yarn 會給我一個警告。但是在升級依賴項時向所有 n
工作區添加相同的依賴項(有很多並且可能會增長)似乎很乏味且難以維護。
是正確的做法添加共享依賴項(例如,typescript
,或 jest
或 serverless
參考解法
方法 1:
After a half‑day search and trying, I found multiple ways to manage shared dependencies
1. Sync dependency version with syncpack
https://github.com/JamieMason/syncpack/
Given the fact that yarn workspaces will share the dependencies if their versions are the same (see https://classic.yarnpkg.com/lang/en/docs/workspaces/), all we have to do is to keep the dependency versions in sync to make dependencies sharing, which is exactly what syncpack does.
I found this is the least harmful way to make sharing dependencies works, while other methods require some degree of twisting package.json.
2. Use peer dependencies
For each package, set sharing dependencies as peerDependencies with version “*”, and set root workspace set the real dependencies. For example:
# ./package.json
{
...
"workspaces": ["packages/*"],
"dependencies": [
"some‑lib": "^1.0.0",
]
}
# ./packages/pkg‑a/package.json
{
...
"peerDependencies": [
"some‑lib": "*",
]
}
and yarn install
at workspace root.
3. Share script (require yarn v2)
See https://yarnpkg.com/getting‑started/qa#how‑to‑share‑scripts‑between‑workspaces
Miscellaneous
yarn provides workspace cli to add/remove package, see https://classic.yarnpkg.com/lang/en/docs/cli/workspace/
yarn workspace awesome‑package add react react‑dom ‑‑dev
yarn workspace web‑project remove some‑package