Skip to content

在 macOS 上安装 fnm

fnm 在 macOS 上有多种安装方式,本指南将帮助你选择最适合的方法。

安装方式

使用 Homebrew(推荐)

Homebrew 是 macOS 上最流行的包管理器:

bash
# 安装 fnm
brew install fnm

使用 curl 脚本

无需包管理器,直接安装:

bash
curl -fsSL https://fnm.vercel.app/install | bash

使用 MacPorts

如果你使用 MacPorts:

bash
port install fnm

手动下载

  1. 访问 fnm Releases 页面
  2. 下载 fnm-macos.zip(Intel)或 fnm-macos-arm64.zip(Apple Silicon)
  3. 解压并移动到 PATH 目录:
bash
# Apple Silicon (M1/M2/M3)
unzip fnm-macos-arm64.zip
sudo mv fnm /usr/local/bin

# Intel Mac
unzip fnm-macos.zip
sudo mv fnm /usr/local/bin

配置 Shell

macOS 默认使用 Zsh,但也支持 Bash 和 Fish。

Zsh(默认)

编辑 ~/.zshrc

bash
# 打开配置文件
nano ~/.zshrc

# 添加以下内容
eval "$(fnm env --use-on-cd)"

重新加载配置:

bash
source ~/.zshrc

Bash

编辑 ~/.bashrc~/.bash_profile

bash
# 打开配置文件
nano ~/.bash_profile

# 添加以下内容
eval "$(fnm env --use-on-cd)"

重新加载配置:

bash
source ~/.bash_profile

Fish

编辑 ~/.config/fish/config.fish

fish
# 打开配置文件
nano ~/.config/fish/config.fish

# 添加以下内容
fnm env --use-on-c | source

重新加载配置:

fish
source ~/.config/fish/config.fish

Shell 补全

Zsh 补全

bash
# 添加补全脚本
fnm completions --shell zsh > ~/.zsh/completion/_fnm

# 确保 fpath 包含补全目录
# 在 ~/.zshrc 中添加
fpath=(~/.zsh/completion $fpath)

# 启用补全
autoload -U compinit && compinit

或者使用 oh-my-zsh:

bash
# 创建补全目录
mkdir -p ~/.oh-my-zsh/completions

# 生成补全脚本
fnm completions --shell zsh > ~/.oh-my-zsh/completions/_fnm

Bash 补全

bash
# 添加补全脚本
fnm completions --shell bash >> ~/.bashrc

# 重新加载
source ~/.bashrc

Fish 补全

bash
# 生成补全脚本
fnm completions --shell fish > ~/.config/fish/completions/fnm.fish

# 重新加载
source ~/.config/fish/config.fish

使用国内镜像

在中国大陆,建议配置镜像加速下载:

bash
# 在 Shell 配置文件中添加
export FNM_NODE_DIST_MIRROR=https://npmmirror.com/mirrors/node

# 或者在 eval 时指定
eval "$(fnm env --use-on-cd --node-dist-mirror=https://npmmirror.com/mirrors/node)"

Apple Silicon (M1/M2/M3) 注意事项

fnm 完全支持 Apple Silicon:

  • 自动检测系统架构
  • 安装原生 ARM64 版本的 Node.js
  • 支持 x64 模拟(通过 Rosetta 2)

安装 x64 版本

如果需要 x64 版本的 Node.js:

bash
# 安装 x64 架构的 Node.js
fnm install 20 --arch=x64

验证安装

bash
# 检查 fnm 版本
fnm --version

# 安装 Node.js
fnm install --lts

# 验证 Node.js
node --version
npm --version

常见问题

命令找不到

如果安装后 fnm 命令找不到:

bash
# 检查 fnm 路径
which fnm

# 如果使用 curl 安装,确保 PATH 包含
echo $PATH

# 手动添加到 PATH
export PATH="$HOME/.fnm:$PATH"

权限问题

如果遇到权限问题:

bash
# 确保目录有正确权限
chmod +x ~/.fnm/fnm

Homebrew 安装后不生效

bash
# 重新链接
brew unlink fnm && brew link fnm

# 检查安装
brew list fnm

下一步

安装完成后,你可以:

相关链接