NVM 使用指南
本章节将介绍 NVM 的常用命令和使用方法。以下命令适用于所有操作系统,但 Windows 版本的一些命令可能略有不同。
常用命令
查看可用命令
bash
nvm
执行 nvm
命令而不加任何参数将显示所有可用的命令和相关帮助信息。
查看可安装的 Node.js 版本
bash
nvm list available
此命令会显示可以安装的 Node.js 版本列表。
安装 Node.js
bash
# 安装最新版本的 Node.js
nvm install latest
# 安装指定版本的 Node.js
nvm install 14.17.0
# 安装最新的 LTS 版本
nvm install lts
安装时会显示 Node.js 和 npm 的相应版本号。
查看已安装的版本
bash
# 简写命令
nvm ls
# 全名命令
nvm list
此命令会列出已安装的所有 Node.js 版本,当前使用的版本前面会有一个星号(*)标记。
切换 Node.js 版本
bash
# 使用指定版本
nvm use 14.17.0
# 使用指定版本简写
nvm use 14
# 使用最新版本
nvm use latest
# 使用最新的 LTS 版本
nvm use lts
切换版本后,当前使用的 Node.js 版本前面会显示星号(*)标记。
设置默认 Node.js 版本
bash
nvm alias default 14.17.0
设置默认版本后,每次打开新终端时,将自动使用该版本的 Node.js。
卸载 Node.js 版本
bash
nvm uninstall 14.17.0
此命令将卸载指定版本的 Node.js。
高级用法
项目特定版本
您可以在项目根目录创建 .nvmrc
文件,并在其中指定该项目应使用的 Node.js 版本。这样,在项目目录中执行 nvm use
命令时,NVM 将自动使用 .nvmrc
中指定的版本。
例如,在 .nvmrc
文件中写入:
14.17.0
然后在项目目录中执行:
bash
nvm use
NVM 将自动切换到 14.17.0 版本的 Node.js。
使用镜像加速
如果您在中国大陆地区,可以通过设置镜像来加速 Node.js 的下载:
Windows 版本
bash
# 设置 npm 镜像
nvm npm_mirror https://npmmirror.com/mirrors/npm/
# 设置 Node.js 镜像
nvm node_mirror https://npmmirror.com/mirrors/node/
Linux/MacOS 版本
在 ~/.bashrc
或 ~/.zshrc
文件中添加:
bash
export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node
export NVM_NPM_MIRROR=https://npmmirror.com/mirrors/npm
然后运行 source ~/.bashrc
或 source ~/.zshrc
使配置生效。
安装时指定架构
在 Windows 上,您可以指定安装 32 位或 64 位版本的 Node.js:
bash
# 安装 32 位版本
nvm install 14.17.0 32
# 安装 64 位版本
nvm install 14.17.0 64
运行特定版本的 Node.js
不切换当前版本的情况下,运行特定版本的 Node.js:
bash
nvm run 14.17.0 app.js
此命令将使用 14.17.0 版本的 Node.js 运行 app.js 文件,而不会更改当前使用的版本。