如何在 Lerna + Yarn Workspaces repo 中安装 npm 包?

How to install npm package in Lerna + Yarn Workspaces repo?

如果我想给一个包添加依赖,我需要cd进入那个目录然后运行yarn add <package>吗?或者,是否有我可以在根目录中 运行 的命令,可能带有 --workspace=<workspace-name>?

之类的标志

您不需要cd进入包目录和运行yarn add <package>。您可以在多包存储库的根路径中使用 lerna add command with --scope 过滤器选项。

Add a single dependency to matched packages

例如对packages/pkg-a添加chalk依赖:

 [main] ⚡  npx lerna add chalk --scope pkg-a
lerna notice cli v3.22.1
lerna notice filter including "pkg-a"
lerna info filter [ 'pkg-a' ]
lerna info Adding chalk in 1 package
lerna info bootstrap root only
npm WARN @octokit/plugin-request-log@1.0.3 requires a peer of @octokit/core@>=3 but none is installed. You must install peer dependencies yourself.

added 6 packages from 3 contributors and audited 1319 packages in 4.811s
found 0 vulnerabilities

安装后,会在packages/pkg-a/package.json文件的dependencies字段中添加chalk

{
  "name": "pkg-a",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node app.js",
    "test": "jest --config jest.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "chalk": "^4.1.0",
    "express": "^4.17.1"
  }
}

lerna版本:

[main] ⚡  npx lerna -v     
3.22.1