Yarn 参考文档

第一部分:概述与比较

Yarn 1.x vs Yarn 2+ (Berry) 的主要差异

特性 Yarn 1.x Yarn 2+ (Berry)
架构 基于node_modules 支持node_modulesPnP (Plug’n’Play)
配置文件 .yarnrc .yarnrc.yml (YAML格式)
插件系统 不支持 内置插件系统
工作区 有限支持 完整支持Monorepo
安装速度 更快(并行安装优化)
缓存机制 基于本地缓存 改进的全局缓存
版本管理 Semver 支持Semver和workspace:*

Yarn 与 npm、pnpm 的核心区别和优势对比

特性 Yarn npm pnpm
安装速度 中等 最快
并行安装 ✅ (npm 6+)
离线模式
确定性安装 ✅ (yarn.lock) ✅ (package-lock.json) ✅ (pnpm-lock.yaml)
工作区支持 ✅ (npm 7+)
依赖共享 ❌ (node_modules重复) ❌ (node_modules重复) ✅ (硬链接共享)
插件系统 ✅ (Yarn 2+)
PnP支持 ✅ (Yarn 2+)

版本选择建议

  • Yarn 1.x: 适用于需要稳定、广泛兼容的项目,特别是依赖于传统node_modules结构的项目
  • Yarn 2+: 适用于新项目,特别是需要Monorepo支持、PnP优化或插件系统的项目
  • 考虑因素: 团队熟悉度、项目复杂度、依赖生态兼容性

第二部分:安装与配置

系统要求与安装

各操作系统安装方法

macOS:

bash
# 使用Homebrew安装
brew install yarn

# 或使用npm安装
npm install -g yarn

Windows:

bash
# 使用Chocolatey安装
choco install yarn

# 或使用Scoop安装
scoop install yarn

# 或使用npm安装
npm install -g yarn

Linux:

bash
# Debian/Ubuntu
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update && sudo apt install yarn

# CentOS/RHEL
sudo wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo
sudo yum install yarn

版本检查和升级命令

bash
# 检查当前版本
yarn --version

# 升级到最新版Yarn 1.x
yarn set version latest

# 升级到Yarn 2+
yarn set version berry

# 升级到特定版本
yarn set version 2.4.2

多版本管理工具使用

与nvm兼容性:

bash
# 安装特定Node.js版本
nvm install 14
nvm use 14

# 安装Yarn
npm install -g yarn

# 切换Node.js版本后,重新安装Yarn
nvm use 16
npm install -g yarn

初始化配置

yarnrc配置文件详解

Yarn 1.x: 使用.yarnrc文件(INI格式) Yarn 2+: 使用.yarnrc.yml文件(YAML格式)

全局配置项说明

yaml
# .yarnrc.yml 示例配置

# 全局依赖安装目录
prefix: ~/.yarn

# 镜像源配置
npmRegistryServer: https://registry.npmmirror.com

# 网络超时设置
timeout: 30000

# 启用PnP模式
nodeLinker: pnp

# 缓存目录
cacheFolder: ~/.yarn/cache

# 忽略引擎检查
ignoreEngines: false

镜像源配置(国内用户优化)

bash
# Yarn 1.x
yarn config set registry https://registry.npmmirror.com

# Yarn 2+
yarn config set npmRegistryServer https://registry.npmmirror.com

网络代理设置

bash
# 设置HTTP代理
yarn config set proxy http://proxy.example.com:8080
yarn config set https-proxy https://proxy.example.com:8080

# 清除代理设置
yarn config delete proxy
yarn config delete https-proxy

第三部分:核心命令速查表

1. 项目初始化与配置

类别 命令格式 参数说明 使用示例
项目初始化与配置 yarn init 初始化新项目 yarn init -y(快速初始化)
项目初始化与配置 yarn set version <version> 设置Yarn版本 yarn set version berry
项目初始化与配置 yarn config <cmd> 配置Yarn yarn config list(查看配置)
项目初始化与配置 yarn policies set-version <version> 锁定Yarn版本 yarn policies set-version v1.22.10

2. 依赖管理

类别 命令格式 参数说明 使用示例
依赖管理 yarn add <package> 添加依赖 yarn add react
依赖管理 yarn add -D <package> 添加开发依赖 yarn add -D @types/react
依赖管理 yarn add -P <package> 添加peer依赖 yarn add -P react-dom
依赖管理 yarn remove <package> 删除依赖 yarn remove lodash
依赖管理 yarn upgrade <package> 更新依赖 yarn upgrade react
依赖管理 yarn upgrade-interactive 交互式更新 yarn upgrade-interactive --latest
依赖管理 yarn install 安装所有依赖 yarn install --frozen-lockfile

3. 脚本执行

类别 命令格式 参数说明 使用示例
脚本执行 yarn run <script> 执行脚本 yarn run build
脚本执行 yarn <script> 简写形式 yarn build
脚本执行 yarn exec <cmd> 执行命令 yarn exec tsc
脚本执行 yarn create <package> 创建新项目 yarn create react-app my-app

4. 工作区管理

类别 命令格式 参数说明 使用示例
工作区管理 yarn workspace <name> <cmd> 在工作区执行命令 yarn workspace web add react
工作区管理 yarn workspaces <cmd> 在所有工作区执行命令 yarn workspaces run build
工作区管理 yarn workspaces info 查看工作区信息 yarn workspaces info

5. 发布相关

类别 命令格式 参数说明 使用示例
发布相关 yarn publish 发布包 yarn publish --tag beta
发布相关 yarn npm login 登录npm yarn npm login
发布相关 yarn npm logout 退出npm yarn npm logout
发布相关 yarn npm publish 发布到npm yarn npm publish --access public

6. 缓存与清理

类别 命令格式 参数说明 使用示例
缓存与清理 yarn cache list 查看缓存 yarn cache list --pattern react
缓存与清理 yarn cache clean 清理缓存 yarn cache clean
缓存与清理 yarn cache dir 查看缓存目录 yarn cache dir
缓存与清理 yarn autoclean 清理不必要文件 yarn autoclean --init

7. 安全检查

类别 命令格式 参数说明 使用示例
安全检查 yarn audit 检查依赖漏洞 yarn audit --level moderate
安全检查 yarn why <package> 查看依赖原因 yarn why lodash
安全检查 yarn licenses list 查看许可证 yarn licenses list

第四部分:工作区(Workspaces)详解

Monorepo项目结构配置

yaml
# package.json (根目录)
{
  "name": "my-monorepo",
  "private": true,
  "workspaces": [
    "packages/*",
    "apps/*"
  ],
  "scripts": {
    "build": "yarn workspaces run build",
    "test": "yarn workspaces run test"
  }
}

工作区间的依赖管理

bash
# 添加共享依赖到根目录
yarn add -D typescript jest

# 在特定工作区添加依赖
yarn workspace web add react
yarn workspace api add express

# 工作区之间的依赖
yarn workspace web add @my-monorepo/utils@workspace:*

常见工作区操作模式

安装所有依赖:

bash
yarn install

构建所有工作区:

bash
yarn build

测试特定工作区:

bash
yarn workspace web test

清理所有工作区:

bash
yarn workspaces run clean

与Lerna等工具的配合使用

bash
# 安装Lerna
yarn add -D lerna

# 初始化Lerna
lerna init

# 配置Lerna使用Yarn工作区
# lerna.json
{
  "packages": [
    "packages/*"
  ],
  "version": "independent",
  "npmClient": "yarn",
  "useWorkspaces": true
}

第五部分:插件系统(Yarn 2+)

核心插件列表及功能

插件名称 功能描述 安装命令
@yarnpkg/plugin-typescript TypeScript支持 yarn plugin import typescript
@yarnpkg/plugin-workspace-tools 工作区工具 yarn plugin import workspace-tools
@yarnpkg/plugin-version 版本管理 yarn plugin import version
@yarnpkg/plugin-npm-cli npm CLI兼容 内置
@yarnpkg/plugin-node-modules node_modules支持 内置

自定义插件开发指南

创建简单插件:

typescript
// plugin-example.ts
import { Plugin } from '@yarnpkg/core';

export const plugin: Plugin = {
  commands: [
    require('./commands/example').default,
  ],
};

注册插件:

bash
yarn plugin import ./plugin-example.js

常用社区插件推荐

  • @yarnpkg/plugin-dlx: 改进的yarn dlx命令
  • @yarnpkg/plugin-outdated: 更好的依赖过时检查
  • @yarnpkg/plugin-constraints: 工作区约束管理
  • @yarnpkg/plugin-interactive-tools: 交互式工具增强

第六部分:最佳实践

依赖管理

版本锁定策略

yarn.lock详解:

  • 确保团队成员使用相同版本的依赖
  • 防止意外的依赖更新导致构建失败
  • 提高安装速度(无需解析版本)

依赖类型区分

json
{
  "dependencies": {
    "react": "^17.0.0"  // 生产依赖
  },
  "devDependencies": {
    "@types/react": "^17.0.0",  // 开发依赖
    "webpack": "^5.0.0"  // 构建工具
  },
  "peerDependencies": {
    "react-dom": "^17.0.0"  // 对等依赖
  }
}

选择性依赖解析

json
// package.json
{
  "resolutions": {
    "lodash": "^4.17.21",
    "**/react": "^17.0.0"
  }
}

离线安装配置

bash
# 启用离线模式
yarn install --offline

# 预下载依赖
yarn install --prefer-offline

性能优化

缓存机制和配置

yaml
# .yarnrc.yml
cacheFolder: ~/.yarn/cache
httpTimeout: 60000

安装加速技巧

bash
# 并行安装优化
yarn install --network-concurrency 16

# 跳过完整性检查
yarn install --skip-integrity-check

# 使用PnP模式(Yarn 2+)
yarn set version berry
yarn install

PnP模式详解及迁移指南

启用PnP模式:

bash
yarn set version berry
yarn config set nodeLinker pnp
yarn install

迁移步骤:

  1. 备份现有项目
  2. 升级到Yarn 2+
  3. 启用PnP模式
  4. 更新编辑器支持(安装PnP插件)
  5. 测试构建和运行

团队协作

统一的团队配置方案

yaml
# .yarnrc.yml
npmRegistryServer: https://registry.npmmirror.com
nodeLinker: pnp
strictSemver: true
ignoreEngines: false

CI/CD集成建议

yaml
# GitHub Actions 示例
name: CI

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set up Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '14'
      - name: Install Yarn
        run: npm install -g yarn
      - name: Install dependencies
        run: yarn install --frozen-lockfile
      - name: Build
        run: yarn build
      - name: Test
        run: yarn test

依赖安全检查集成

bash
# 集成到CI流程
yarn audit --level high

# 使用Snyk进行更深入的检查
npx snyk test

第七部分:故障排除

常见错误代码及解决方案

错误代码 错误信息 解决方案
ENOENT 找不到模块 检查依赖是否正确安装,运行yarn install
EACCES 权限不足 使用sudo或检查文件权限
ETIMEDOUT 网络超时 检查网络连接,增加超时时间yarn config set timeout 60000
ERESOLVE 依赖解析失败 检查依赖版本冲突,使用yarn why <package>查看原因

网络问题处理

bash
# 检查网络连接
ping registry.npmmirror.com

# 更换镜像源
yarn config set npmRegistryServer https://registry.npmmirror.com

# 检查代理设置
yarn config list | grep proxy

版本冲突解决

bash
# 查看依赖树
yarn list --pattern <package>

# 使用resolutions强制版本
yarn add -D resolutions
# 在package.json中添加resolutions字段

缓存清理与重建

bash
# 清理缓存
yarn cache clean

# 删除node_modules和lock文件
rm -rf node_modules yarn.lock

# 重新安装
yarn install

第八部分:迁移指南

从npm迁移到Yarn

bash
# 1. 安装Yarn
npm install -g yarn

# 2. 删除node_modules和package-lock.json
rm -rf node_modules package-lock.json

# 3. 安装依赖
yarn install

# 4. 更新npm脚本
# 将所有npm命令替换为yarn命令

从Yarn 1.x迁移到Yarn 2+

bash
# 1. 备份项目
cp -r my-project my-project-backup

# 2. 升级到Yarn 2+
yarn set version berry

# 3. 安装依赖
yarn install

# 4. 配置PnP(可选)
yarn config set nodeLinker pnp

# 5. 测试构建和运行
yarn build
yarn test

从Yarn迁移到其他包管理器

迁移到pnpm:

bash
# 安装pnpm
npm install -g pnpm

# 删除node_modules和yarn.lock
rm -rf node_modules yarn.lock

# 安装依赖
pnpm install

迁移到npm:

bash
# 删除node_modules和yarn.lock
rm -rf node_modules yarn.lock

# 安装依赖
npm install

附录

1. 命令别名速查

命令 别名
yarn install yarn
yarn add yarn add
yarn remove yarn remove
yarn run yarn
yarn global add yarn global add

2. 配置文件完整示例

yaml
# .yarnrc.yml 完整配置

# 基础配置
prefix: ~/.yarn
timeout: 60000
ignoreEngines: false
strictSemver: true

# 网络配置
npmRegistryServer: https://registry.npmmirror.com
proxy: http://proxy.example.com:8080
httpsProxy: https://proxy.example.com:8080
noProxy: localhost,127.0.0.1

# 依赖管理
nodeLinker: pnp
nmMode: hardlinks-local
extraNodeModules: {}

# 缓存配置
cacheFolder: ~/.yarn/cache
cachePattern: "*.tgz"

# 脚本配置
shell: bash
scriptShell: bash

# 日志配置
logLevel: info

3. 常用第三方工具集成

  • ESLint: yarn add -D eslint eslint-plugin-react
  • Prettier: yarn add -D prettier eslint-config-prettier
  • Jest: yarn add -D jest @types/jest babel-jest
  • Webpack: yarn add -D webpack webpack-cli webpack-dev-server
  • Rollup: yarn add -D rollup @rollup/plugin-node-resolve

4. 官方资源链接


文档更新时间: 2026-02-03 适用Yarn版本: 1.x, 2+

最后更新:2026-02-07