Skip to content
On this page

Yarn Workspaces 详解

简介

Yarn Workspaces 是 Yarn 包管理器的一个功能,允许在单个项目中管理多个包。它提供了一种高效的方式来处理 monorepo,通过将相关的包组织在一个存储库中,同时保持它们的独立性。

启用 Workspaces

在根目录的 package.json 文件中添加 workspaces 配置:

json
{
  "private": true,
  "workspaces": [
    "packages/*",
    "examples/*"
  ]
}

项目结构示例

my-monorepo/
├── package.json
├── packages/
│   ├── package-a/
│   │   ├── src/
│   │   ├── package.json
│   │   └── README.md
│   └── package-b/
│       ├── src/
│       ├── package.json
│       └── README.md
└── yarn.lock

核心功能

1. 依赖提升(Hoisting)

Yarn 会自动将共享依赖提升到根目录,减少磁盘空间占用和安装时间。

2. 跨包链接

在 workspaces 内的包可以自动相互引用,无需发布到 npm。

3. 一次性安装

使用 yarn install 会为所有工作区安装依赖。

常用命令

1. 安装依赖

bash
yarn install

2. 在特定包中运行脚本

bash
yarn workspace <package-name> <script>

3. 在所有包中运行脚本

bash
yarn workspaces run <script>

4. 添加依赖到特定包

bash
yarn workspace <package-name> add <dependency>

5. 添加开发依赖到特定包

bash
yarn workspace <package-name> add <dependency> --dev

高级配置

1. 工作区约束

在根 package.json 中配置:

json
{
  "private": true,
  "workspaces": {
    "packages": [
      "packages/*"
    ],
    "nohoist": [
      "**/react-native"
    ]
  }
}

2. 跨包引用

在包的 package.json 中直接引用其他包:

json
{
  "name": "package-b",
  "dependencies": {
    "package-a": "*"
  }
}

与 Lerna 集成

Yarn Workspaces 可以与 Lerna 结合使用:

json
{
  "private": true,
  "workspaces": [
    "packages/*"
  ],
  "devDependencies": {
    "lerna": "^5.0.0"
  }
}

在 lerna.json 中配置:

json
{
  "packages": [
    "packages/*"
  ],
  "version": "0.0.0",
  "npmClient": "yarn",
  "useWorkspaces": true
}

性能优化

1. 缓存策略

Yarn 使用内容地址缓存,提高安装速度。

2. 并行安装

自动并行安装依赖,充分利用系统资源。

3. 零安装(Zero-Installs)

Yarn 2+ 支持零安装,通过 .yarn/cache 目录加速项目初始化。

最佳实践

1. 包命名约定

使用一致的命名约定,如 @org/package-name

2. 依赖管理

  • 将公共依赖定义在根目录
  • 避免版本冲突
  • 定期更新依赖

3. CI/CD 集成

  • 使用 yarn workspaces run test 运行所有包的测试
  • 实施增量构建策略
  • 基于更改的工作区过滤

优缺点

优点

  • 简单易用的配置
  • 优秀的性能表现
  • 与 Yarn 生态系统深度集成
  • 自动依赖提升

缺点

  • 仅限 Yarn 用户
  • 相比 Lerna 缺少版本和发布管理功能
  • 对非 JavaScript 项目支持有限

与其他工具对比

Yarn Workspaces 专注于依赖管理和包安装,而 Lerna 专注于版本管理和发布。两者可以结合使用,Yarn 负责依赖,Lerna 负责版本.