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

下一步

安裝完成後,你可以:

相關鏈接