MacOS 下使用nvm管理node环境

node版本变化有些快,需要切换不同版本构建项目,使用nvm管理node是一个比较成熟的方案。

1. 安装nvm

1.1 MacOS

  • brew安装
brew install nvm 
  • 官方脚本
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash

1.2 Linux

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash

1.3 安装注意事项

==> Caveats
Please note that upstream has asked us to make explicit managing
nvm via Homebrew is unsupported by them and you should check any
problems against the standard nvm install method prior to reporting.

You should create NVM's working directory if it doesn't exist:

  mkdir ~/.nvm

Add the following to ~/.zshrc or your desired shell
configuration file:

  export NVM_DIR="$HOME/.nvm"
  [ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && . "/opt/homebrew/opt/nvm/nvm.sh"  # This loads nvm
  [ -s "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" ] && . "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm"  # This loads nvm bash_completion

You can set $NVM_DIR to any location, but leaving it unchanged from
/opt/homebrew/opt/nvm will destroy any nvm-installed Node installations
upon upgrade/reinstall.

Type `nvm help` for further information.

  • 创建nvm目录
mkdir ~/.nvm
  • 处理~/.zshrc或者~/.bashrc(此处zsh举例)
  export NVM_DIR="$HOME/.nvm"
  [ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && . "/opt/homebrew/opt/nvm/nvm.sh"  # This loads nvm
  [ -s "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" ] && . "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm"  # This loads nvm bash_completion

1.4 nvm使用说明

# 显示服务器端版本列表
nvm ls-remote
# 安装指定版本
nvm install vXX.XX.XX
# 设置默认的版本
nvm alias default vXX.XX.XX
# 显示本地下载的版本列表
nvm list

2. 配置镜像加速

2.1 nvm加速

需要设置环境变量NVM_NODEJS_ORG_MIRROR

# 临时设置
export NVM_NODEJS_ORG_MIRROR=http://npm.taobao.org/mirrors/node
# 配置上述命令到bashrc/zshrc中保持生效

2.2 npm加速

# 查看当前registry
npm config -g get registry
# 设置registry
npm config -g set registry https://registry.npm.taobao.org

2.3 yarn配置

# 安装yarn
npm install -g yarn
# 查看yarn registry
yarn config get registry
# 设置yarn registry
yarn config set registry http://registry.npm.taobao.org/