Nodejs包管理器们

太乱了,真得…

异同

npm 是一个包管理器。Node.js 自带。
cnpm 是 npm 的阿里版,用的阿里源,用法与 npm 一致。
yarn 是另一个包管理器,不自带。可以单独装,也可以用 npm 装。比 npm 快很多。
tyarn 是 yarn 的阿里版,用的阿里源,用法与 yarn 一致。

安装

1
2
3
4
5
6
7
8
# cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org

# yarn
npm i yarn -g

# tyarn
npm i yarn tyarn -g

换源

1
2
3
4
5
6
7
8
9
10
11
12
13
# 查看当前源
npm config get registry

# npm 换淘宝源
npm config set registry https://registry.npm.taobao.org

# 换回来
npm config set registry https://registry.npmjs.org

# yarn 同理
yarn config get registry
yarn config set registry https://registry.npm.taobao.org
yarn config set registry https://registry.npmjs.org

还有一个指定目录换源的方法。
新建一个.npmrc到需要 yarn 的目录。

1
2
# .npmrc
registry=https://registry.npm.taobao.org

设置代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# npm 设置代理
npm config set proxy=http://127.0.0.1:8087
npm config set https-proxy=http://127.0.0.1:8087

# npm 取消代理
npm config delete proxy
npm config delete https-proxy

# yarn 设置代理
yarn config set proxy http://XXX
yarn config set https-proxy http://XXX

# yarn 取消代理
yarn config delete proxy
yarn config delete https-proxy

其他

  • npm
    • ~会匹配最近的小版本依赖包,比如~1.2.3会匹配所有1.2.x版本,但是不包括1.3.0
    • ^会匹配最新的大版本依赖包,比如^1.2.3会匹配所有1.x.x的包,包括1.3.0,但是不包括2.0.0
    • *这意味着安装最新版本的依赖包

装依赖遇到困难时,至少有以下方法。

  • 使用 cnpm / tyarn
  • 更换淘宝源 / .npmrc 设置源
  • 设置代理

参考

  • 博客园 - 亦虚
  • 掘金 - fen 同学