yarn 与 npm 功能等价但实现不同:它采用并行下载并带本地缓存,重复安装同一个包几乎秒装完成;lockfile 从诞生第一天就是默认行为,比 npm 更早把整棵依赖树锁死。常用命令对照:yarn 对应 npm install,yarn add 对应 npm install 包名,yarn remove 对应 npm uninstall。
yarn workspace 原生支持 monorepo,一条命令管理多个子包的依赖;yarn dlx 对应 npx 可执行远程包。目前 yarn 2 及以上版本引入了即插即用(Plug and Play)机制取代 node_modules 目录,但多数项目仍在使用经典版 yarn 1,两者命令差异不大而底层机制完全不同。
// 常用命令对照(npm -> yarn) // npm install -> yarn (利用缓存并行安装) // npm install lodash -> yarn add lodash // npm uninstall lodash -> yarn remove lodash // npm run dev -> yarn dev (yarn 可省略 run) // npx cowsay -> yarn dlx cowsay // package.json 中声明 monorepo 工作区 { "name": "root", "private": true, "workspaces": ["packages/*"] }