在上一篇文章《3 分鐘掌握 Node.js 版本的區別》中介紹了 Node.js 版本分爲 LTS 和 Current 系列,當我們需要在本地開發環境同時安裝 LTS 版本和 Current 版本時,就需要對 Node.js 版本進行版本管理。
比如本地需要同時安裝 Node.js 8.0.0 和 Node.js 17.0.0。
爲了能夠對 Node.js 版本進行版本管理,我整理了 3 款非常實用的 Node.js 版本管理工具,讓大家能夠自由的切換本地環境不同的 Node.js 版本。
1. nvm
⭐ Github stars: 60K+
nvm 是一款 Node.js 版本管理工具,允許用戶通過命令行快速安裝、切換和管理不同的 Node.js 版本。
(圖片來自:github)
nvm 只適用於 macOS 和 Linux 用戶的項目,如果是 Windows 用戶,可以使用 nvm-windows 、nodist 或 nvs 替換。
安裝方式
macOS 下載方式:
# 方式1 瀏覽器打開下面鏈接下載
https://github.com/nvm-sh/nvm/blob/v0.39.1/install.sh
# 下載完成後,通過命令安裝
sh install.sh
# 方式2 推薦
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
# 方式3
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
安裝過程中如果遇到一些奇怪的問題,可以查看下 nvm 補充說明。
常用命令
nvm ls # 查看版本安裝所有版本
nvm ls-remote # 查看遠程所有的 Node.js 版本
nvm install 17.0.0 # 安裝指定的 Node.js 版本
nvm use 17.0.0 # 使用指定的 Node.js 版本
nvm alias default 17.0.0 # 設置默認 Node.js 版本
nvm alias dev 17.0.0 # 設置指定版本的別名,如將 17.0.0 版本別名設置爲 dev
2. n
⭐ Github stars: 16.7K+
n 是一款交互式的 Node.js 版本管理工具,沒有子腳本,沒有配置文件,也沒有複雜的 API,使用起來非常簡單。
n 只適用於 macOS 和 Linux ,不適用於 Windows。
安裝方式
可以使用 npm 直接安裝到全局:
npm install n -g
常用命令
n # 顯示所有已下載版本
n 10.16.0 # 下載指定版本
n lts # 查看遠程所有 LTS Node.js 版本
n run 10.16.0 # 運行指定的 Node.js 版本
輸入 n -h
查看幫助信息,主要命令如下:
n Display downloaded Node.js versions and install selection
n latest Install the latest Node.js release (downloading if necessary)
n lts Install the latest LTS Node.js release (downloading if necessary)
n <version> Install Node.js <version> (downloading if necessary)
n install <version> Install Node.js <version> (downloading if necessary)
n run <version> [args ...] Execute downloaded Node.js <version> with [args ...]
n which <version> Output path for downloaded node <version>
n exec <vers> <cmd> [args...] Execute command with modified PATH, so downloaded node <version> and npm first
n rm <version ...> Remove the given downloaded version(s)
n prune Remove all downloaded versions except the installed version
n --latest Output the latest Node.js version available
n --lts Output the latest LTS Node.js version available
n ls Output downloaded versions
n ls-remote [version] Output matching versions available for download
n uninstall Remove the installed Node.js
3. fnm
⭐ Github stars: 8.4K+
fnm 是一款快速簡單 🚀 的 Node.js 版本管理器,使用 Rust 構建。
(圖片來自:freecodecamp)
主要特點包括:
- 🌎 跨平臺支持,包括:macOS、Windows、Linux;
- ✨ 單一文件,輕鬆安裝,即時啓動 ;
- 🚀 以速度爲設計理念;
- 📂 適用於
.node-version
和.nvmrc
文件;
安裝方式
macOS / Linux 環境:
# bash, zsh and fish shells
curl -fsSL https://fnm.vercel.app/install | bash
Windows 環境:
# 管理員模式打開終端,安裝後只能使用管理員模式打開使用
choco install fnm
# 安裝完成還需要手動設置環境變量
Linux/macOS/Windows 環境也可以直接下載二進制文件安裝,下載地址:https://github.com/Schniz/fnm/releases
常用命令
fnm -h # 查看幫助
fnm install 17.0.0 # 安裝指定 Node.js 版本
fnm use 17.0.0 # 使用指定 Node.js 版本
fnm default 17.0.0 # 設置默認 Node.js 版本