安装 nodejs & npm
MacOS
brew install node
Ubuntu
# 添加指定版本的源
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
# 更新源
sudo apt update
# 安装 nodejs
sudo apt install -y nodejs
Arch
sudo pacman -Sy nodejs npm
npm 换源
安装 nrm 源管理工具
Nodejs nrm 是一个管理 npm 源的工具。由于 npm 在国内的速度较慢,很多开发者会使用淘宝的 npm 镜像源,但是也会遇到一些问题,例如某些包在淘宝镜像源中不存在,或者淘宝镜像源本身也会有问题。
Nodejs nrm 提供了一个命令行工具,可以方便地切换不同的 npm 源,在不同的场景下使用不同的源。使用 nrm 可以列出当前已有的所有源并切换到指定源,也可以添加自定义的源,并在多个源之间轻松切换。
通过使用 nrm,开发者可以更加方便地管理 npm 源,提高开发效率。
安装 nrm:
npm install -g nrm
通过 nrp -v
查看是否安装
列出已有的源:
nrm ls
输出以下结果:
npm ---------- https://registry.npmjs.org/
yarn --------- https://registry.yarnpkg.com/
tencent ------ https://mirrors.cloud.tencent.com/npm/
cnpm --------- https://r.cnpmjs.org/
* taobao ------- https://registry.npmmirror.com/
npmMirror ---- https://skimdb.npmjs.com/registry/
以上输出结果中, 第一列为镜像源的名称, 最后面的是镜像源的 URL 地址, 开头带 *
的是正在使用的源.
查看当前使用的源名称:
nrm current
输出以下结果:
You are using taobao registry.
以上输出结果告诉我们正在使用的是淘宝的镜像源
查看当前使用源的 URL:
npm config get registry
输出以下结果:
https://registry.npmmirror.com/
以上输出结果告诉我们正在使用的是淘宝的URL镜像源
添加镜像源:
nrm add [镜像源名称] [URL]
例如添加淘宝源:
nrm add taobao https://registry.npmmirror.com/
注: 淘宝之前的镜像源 http://npm.taobao.org 和 http://registry.npm.taobao.org 域名已于 2022 年 05 月 31 日零时起停止服务, 新镜像源地址:
- web 站点: https://npmmirror.com/
- registry 站点: https://registry.npmmirror.com/
- 二进制文件镜像: https://npmmirror.com/mirrors
切换镜像源, 以淘宝为例:
nrm use taobao
测试镜像源速度, 以淘宝为例:
nrm test taobao
输出以下结果:
* taobao ---- 144 ms
删除镜像源, 以淘宝为例:
nrm del taobao
cnpm 安装及配置
cnpm是个中国版的npm,是淘宝定制的 cnpm (gzip 压缩支持) 命令行工具代替默认的 npm. npm和cnpm只是下载器的不同
如果因为网络原因无法使用npm下载,那cnpm这个就派上用场了。
通过cnpm使用淘宝镜像:
npm install -g cnpm --registry=https://registry.npmmirror.com
查看cnpm镜像设置:
cnpm config get registry
yarn 安装及配置
yarn 是一个包管理器,和npm类似;可以让你使用并分享 全世界开发者的(例如 JavaScript)代码。 Yarn 能够快速、安全、 并可靠地完成这些工作(来自官方文档)
安装 yarn:
npm i -g yarn
换源:
yarn config set registry https://registry.npmmirror.com
解决node-sass无法下载下来的问题:
yarn config set sass_binary_site https://cdn.npmmirror.com/dist/node-sass
查看yarn镜像设置:
yarn config get registry