在 VS Code 中使用 nvm(Node Version Manager)控制 Node.js 版本,以下是详细配置指南:
1. 安装 nvm
Windows
bash
# 下载安装包
https://github.com/coreybutler/nvm-windows/releases
macOS/Linux
bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 或
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
2. 常用 nvm 命令
bash
# 查看已安装版本
nvm ls
# 查看可用版本
nvm ls-remote
# 安装特定版本
nvm install 18.16.0
nvm install 20.3.0
# 使用特定版本
nvm use 18.16.0
# 设置默认版本
nvm alias default 18.16.0
# 当前使用版本
nvm current
3. VS Code 配置
方法一:终端集成
- 打开 VS Code 终端(Ctrl + `)
- 直接在终端中使用 nvm 命令切换版本
- 重启终端使版本切换生效
方法二:项目级配置
创建 .nvmrc 文件在项目根目录:
18.16.0
然后在项目目录下执行:
bash
nvm use
方法三:VS Code 自动检测(推荐)
-
安装扩展:
- nvm-node-version(直接支持)
- 或 Shellcheck + Bash IDE
-
配置 settings.json:
json
{
"terminal.integrated.shellArgs.osx": ["-l"],
"terminal.integrated.shellArgs.linux": ["-l"],
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"terminal.integrated.automationShell.windows": "C:\\Windows\\System32\\cmd.exe"
}
4. 常见问题解决
问题1:VS Code 终端未使用正确版本
解决方案:
- 关闭所有 VS Code 实例
- 从命令行启动 VS Code:
bash
code .
问题2:每次新终端都重置版本
解决方案:
- 设置默认版本:
bash
nvm alias default 18.16.0
- 在 shell 配置文件中添加自动加载(~/.bashrc, ~/.zshrc):
bash
# 自动加载 .nvmrc
autoload -U add-zsh-hook
load-nvmrc() {
local node_version="$(nvm version)"
local nvmrc_path="$(nvm_find_nvmrc)"
if [ -n "$nvmrc_path" ]; then
local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
if [ "$nvmrc_node_version" = "N/A" ]; then
nvm install
elif [ "$nvmrc_node_version" != "$node_version" ]; then
nvm use
fi
elif [ "$node_version" != "$(nvm version default)" ]; then
echo "Reverting to nvm default version"
nvm use default
fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc
问题3:调试器使用错误版本
解决方案:
在 launch.json 中指定 runtimeExecutable:
json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/index.js",
"runtimeExecutable": "/Users/username/.nvm/versions/node/v18.16.0/bin/node"
}
]
}
5. 最佳实践
-
项目一致性:
- 每个项目创建
.nvmrc文件 - 在 README 中说明 Node.js 版本要求
- 每个项目创建
-
团队协作:
bash# package.json 中添加 engines 字段 { "engines": { "node": ">=18.0.0" } } -
VS Code 工作区配置:
json// .vscode/settings.json { "files.autoSave": "afterDelay", "editor.formatOnSave": true, "terminal.integrated.defaultProfile.windows": "Command Prompt" } -
自动化脚本 :
在 package.json 中添加:
json{ "scripts": { "env:setup": "nvm install && nvm use", "preinstall": "node -v | grep -q $(cat .nvmrc)" } }
6. 推荐扩展
- nvm-node-version - 自动检测和切换 Node 版本
- Version Lens - 查看 package.json 中的版本信息
- npm - npm 命令支持
- ESLint - 代码检查,版本相关规则
7. 验证配置
bash
# 在 VS Code 终端中运行
node --version
npm --version
nvm current
# 检查路径
which node # macOS/Linux
where node # Windows
按照以上步骤配置,即可在 VS Code 中完美使用 nvm 管理多个 Node.js 版本。