文章目录
说明
- 为什么不推荐用 Homebrew 装 nvm
- 官方不推荐nvm 作者明确写了:
Please note that Homebrew installation is not supported
- 官方不推荐nvm 作者明确写了:
- 权限、路径冲突超多
- M 系列 Mac 的 brew 路径是 /opt/homebrew
- nvm 本身是用户级工具,不是系统级
- 两者混在一起,很容易出现:
nvm use 切换版本不生效
node 命令还是指向系统 /brew 版本
升级 brew 后 nvm 突然失效
- nvm 自己就能完美安装,不需要 brew官方脚本一键安装,干净、独立、不污染系统,卸载也方便。
- 用 brew 装 nvm,出问题网上很难搜到解决方案99% 的教程都是「官方脚本安装」,你用 brew 装出 bug,排查成本巨高。
一、准备工作(安装 Xcode 命令行工具)
打开终端执行
bash
# 安装
xcode-select --install
# 查看是否安装
xcode-select -p
# 输出/Library/Developer/CommandLineTools或者/Applications/Xcode.app/Contents/Developer
# 说明已经安装
# 没有安装会报错
# Can't find the path...
# xcode-select: error: unable to get active developer directory...
二、安装 nvm(官方脚本)
bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
三、配置环境(M3 Mac 必做)
macOS 默认是 zsh,需要把 nvm 初始化加到 ~/.zshrc:
3.1 编辑配置文件
bash
open ~/.zshrc
3.2 在文件末尾添加(如果没有的话):
bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
3.3 让配置立即生效
java
source ~/.zshrc
四、验证安装
bash
nvm --version
出现版本号(如 0.39.7)即成功。
演示
bash
Last login: Wed Apr 1 20:29:25 on ttys000
➜ ~ xcode-select -p
/Library/Developer/CommandLineTools
➜ ~ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 16555 100 16555 0 0 26656 0 --:--:-- --:--:-- --:--:-- 26658
=> Downloading nvm from git to '/Users/shihao/.nvm'
=> 正克隆到 '/Users/shihao/.nvm'...
remote: Enumerating objects: 423, done.
remote: Counting objects: 100% (423/423), done.
remote: Compressing objects: 100% (350/350), done.
remote: Total 423 (delta 59), reused 187 (delta 45), pack-reused 0 (from 0)
接收对象中: 100% (423/423), 413.40 KiB | 1.17 MiB/s, 完成.
处理 delta 中: 100% (59/59), 完成.
* (头指针在 FETCH_HEAD 分离)
master
=> Compressing and cleaning up git repository
=> Appending nvm source string to /Users/shihao/.zshrc
=> Appending bash_completion source string to /Users/shihao/.zshrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:
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
➜ ~ source ~/.zshrc
➜ ~ nvm --version
0.39.7
五、用 nvm 安装 Node.js
bash
# 安装最新 LTS(推荐)
nvm install --lts
# 或安装指定版本(如 20)
nvm install 20
# 设为默认版本
nvm alias default 20
# 查看已装版本
nvm ls
# 切换版本
nvm use 18
# 查看所有可安装的 Node.js 版本
nvm ls-remote
# 只看 LTS 稳定版
nvm ls-remote --lts
node -v # 看当前版本
npm -v # 看npm版本