书格前端

从npm到yarn


从npm到yarn

由于使用NPM在国内的安装速度很慢,找了一些解决方案,因此引出了Yarn + 淘宝源的使用方案,记录一下Yarn使用的方法

  1. Yarn简介
  2. Yarn安装
  3. NPM源配置
  4. Yarn使用

Yarn简介

Yarn是FaceBook推出的一款基于nodejs的依赖管理工具,在npm基础上做了一些改进。Github上的star已经超过30k。

超快

Yarn caches every package it downloads so it never needs to download it again. It also parallelizes operations to maximize resource utilization so install times are faster than ever.

非常安全

Yarn uses checksums to verify the integrity of every installed package before its code is executed.

超可靠

Using a detailed, but concise, lockfile format, and a deterministic algorithm for installs, Yarn is able to guarantee that an install that worked on one system will work exactly the same way on any other system.

详细的优点可参看知乎的评价文章如何评价Facebook推出的JavaScript模块管理器yarn?

Yarn安装

这里列一下MacOS下的安装方法:

使用Homebrew进行安装,如果没有安装Node.js会自动进行安装

brew install yarn

如果已经使用nvm或者类似的工具安装过Node.js,可以选择忽略安装

brew install yarn --without-node

验证是否安装成功:

yarn --version

NPM源配置

有两种方法:

一、直接配置

// 配置registry
npm config set registry https://registry.npm.taobao.org/

npm config get registry

二、使用nrm切换npm源

// 安装nrm
npm i nrm -g

// 列出所有可用的registry
nrm ls

// 使用淘宝源
nrm use taobao

// 测试速度
nrm test

建议使用第二种方案

Yarn使用

列举一些常用的命令:

// 新建一个项目
yarn init

// 添加依赖
yarn add [package]
yarn add [package]@[version]
yarn add [package]@[tag]

// 添加其他类型的依赖到项目中
// 其中dev是开发依赖;peer一般用于开发库;
// optional为可选依赖,安装过程中报错也可忽略
yarn add [package] --dev
yarn add [package] --peer
yarn add [package] --optional

// 升级依赖
yarn upgrade [package]
yarn upgrade [package]@[version]
yarn upgrade [package]@[tag]

// 移除依赖
yarn remove [package]

// 安装一个项目的所有依赖
yarn

// 或者
yarn install