npm 和 yarn 都是 JavaScript 的包管理器,用来下载、安装、管理项目依赖。yarn 最早是 Facebook 为了弥补当时 npm 的不足而开发的,现在两者功能已经很接近,但仍有区别。
一、npm
npm 现属 GitHub/微软,诞生于2010年,随 Node 安装,锁文件为 package-lock.json。
获取registry地址
powershell
npm config get registry
默认registry地址:registry.npmjs.org
设置registry地址
powershell
npm config set registry https://registry.npmmirror.com/
淘宝镜像地址:https://registry.npmmirror.com/
执行 npm config set registry ... ,会写进.npmrc文件
查看更多信息
powershell
npm config list
二、yarn
yarn 为 Facebook 于2016年开发而来,需要单独安装,锁文件为 yarn.lock。
获取registry地址
powershell
yarn config get registry
默认registry地址:https://registry.yarnpkg.com
设置registry地址
powershell
yarn config set registry https://registry.npmmirror.com/
淘宝镜像地址:https://registry.npmmirror.com/
执行 yarn config set registry ... ,会写进.yarnrc文件
查看更多信息
powershell
yarn config list
三、两者的关系
-
镜像源是共享的,npm 和 yarn 都能指向同一个 registry.npmmirror.com,只是各自需要单独配置。
-
npm 和 yarn 默认registry 服务器在国外,访问可能不稳定需要切换回国内地址。
yarn 1.x 在设计时,把自己定位成"npm 的兼容替代品",所以它做了两件事:
- 优先读自己的配置:~/.yarnrc、项目里的 .yarnrc 等
- 再读 npm 的配置作为补充:~/.npmrc、项目里的 .npmrc
如果某个配置项 yarn 自己没定义,它就会去 npm 的配置里找。