[Node.js] 安裝 NVM (Node Version Manager) 來切換 Node.js 版本 for MacOS/CentOS/Ubuntu

Last Updated on 2019-08-25 by OneJar

NVM (Node Version Manager) 是 Node.js 的版本管理工具。Node.js 發展快速,迭代頻繁,很可能同時間在不同專案需要配置不同 Node.js 版本。因此會建議在安裝 Node.js 前先安裝 NVM,利用 NVM 幫助 Node.js 的版本控管和快速切換。

在 Unix-like 作業系統上的 NVM 都是使用 nvm-sh/nvm,因此安裝方式大同小異。

在 Windows 作業系統上的 NVM 是使用 coreybutler/nvm-windows,安裝方式請參考[Node.js] 安裝 NVM (Node Version Manager) 來切換 Node.js 版本 for Windows

For MacOS

Note: 試過 Homebrew 安裝,但不建議,每次重開 terminal 都需要配置一次 nvm use --delete-prefix (可參考正確的安裝和使用nvm)。官方文件其實也說了不建議用 Homebrew:

Homebrew installation is not supported. If you have issues with homebrew-installed nvm, please brew uninstall it, and install it using the instructions below, before filing an issue.

# 如果之前用 homebrew 安裝過 nvm,先移除
$ brew uninstall nvm

# 安裝 NVM
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash

# 檢查檔案最後是否有自動寫入以下 script,如果沒有則手動補上
$ vim ~/.bash_profile
# ```
# export NVM_DIR="$HOME/.nvm"
# [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
# [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
# ```

# 關掉當前 terminal,再次開啟後即 OK
$ nvm --version # 檢查 NVM 版本

# 如果不想中斷 terminal,繼續輸入以下:
$ source ~/.bash_profile
$ nvm --version

For Ubuntu

  • 實測:Ubuntu 16.04
# 安裝 NVM
$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

# 檢查檔案最後是否有自動寫入以下 script,如果沒有則手動補上
$ vim ~/.bashrc
# ```
# export NVM_DIR="$HOME/.nvm"
# [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
# [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
# ```

# 關掉當前 terminal,再次開啟後即 OK
$ nvm --version # 檢查 NVM 版本

# 如果不想中斷 terminal,繼續輸入以下:
$ source ~/.bashrc
$ nvm --version

For RHEL (CentOS/Fedora)

和 Ubuntu 大同小異,細節不再贅述。

  • 實測:RHEL 6
$ curl https://raw.githubusercontent.com/creationix/nvm/v0.25.0/install.sh | bash
$ source ~/.bashrc
$ nvm --version

測試:透過 NVM 安裝 Node.js

$ nvm ls-remote  # 列出目前可供安裝的 Node.js 版本
$ nvm ls              # 列出本機 NVM 已安裝的 Node.js 版本及狀態 (例如目前 active 的是哪一版)

$ nvm install v10.16.0    # 選擇安裝 v10.16.0 版(或你需要的版本)
$ nvm use v8.2.1           # 切換不同 Node.js 版本

$ node -v        # 測試當前 Node.js 的版本
$ npm -v         # 測試當前 NPM 的版本

References

發表留言