Skip to content

在 Windows 上安装 fnm

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

安装方式

使用 winget(推荐)

winget 是 Windows 11 和 Windows 10(1809+)内置的包管理器:

powershell
winget install Schniz.fnm

使用 Scoop

Scoop 是 Windows 上流行的命令行包管理器:

powershell
# 安装 Scoop(如果尚未安装)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
irm get.scoop.sh | iex

# 安装 fnm
scoop install fnm

使用 Chocolatey

Chocolatey 是 Windows 上广泛使用的包管理器:

powershell
# 安装 Chocolatey(如果尚未安装)
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

# 安装 fnm
choco install fnm

使用安装脚本

在 Git Bash 或 WSL 中:

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

手动下载

  1. 访问 fnm Releases 页面
  2. 下载 fnm-windows.zip
  3. 解压到目标目录
  4. 将解压目录添加到系统 PATH

配置 PowerShell

安装完成后,需要配置 PowerShell 环境。

自动配置

运行以下命令将 fnm 配置添加到 PowerShell 配置文件:

powershell
# 创建配置文件(如果不存在)
if (!(Test-Path -Path $PROFILE)) {
    New-Item -ItemType File -Path $PROFILE -Force
}

# 添加 fnm 配置
Add-Content -Path $PROFILE -Value 'fnm env --use-on-cd | Out-String | Invoke-Expression'

# 重新加载配置
. $PROFILE

手动配置

  1. 打开 PowerShell 配置文件:
powershell
notepad $PROFILE
  1. 添加以下内容:
powershell
fnm env --use-on-cd | Out-String | Invoke-Expression
  1. 保存并重新加载:
powershell
. $PROFILE

配置 VS Code

如果你使用 VS Code,需要配置集成终端:

  1. 打开设置(Ctrl + ,
  2. 搜索 terminal.integrated.profiles.windows
  3. 添加或修改 PowerShell 配置:
json
{
  "terminal.integrated.profiles.windows": {
    "PowerShell": {
      "source": "PowerShell",
      "args": ["-NoLogo"]
    }
  }
}

使用国内镜像

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

powershell
# 设置环境变量
[Environment]::SetEnvironmentVariable("FNM_NODE_DIST_MIRROR", "https://npmmirror.com/mirrors/node", "User")

# 或在 PowerShell 配置文件中添加
$env:FNM_NODE_DIST_MIRROR = "https://npmmirror.com/mirrors/node"
fnm env --use-on-cd | Out-String | Invoke-Expression

验证安装

powershell
# 检查 fnm 版本
fnm --version

# 安装 Node.js
fnm install --lts

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

Shell 补全

启用 PowerShell 命令补全:

powershell
# 将补全脚本添加到配置文件
fnm completions --shell powershell | Out-String | Add-Content $PROFILE

# 重新加载配置
. $PROFILE

常见问题

命令找不到

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

  1. 确认 fnm 已添加到 PATH
  2. 重新打开 PowerShell 窗口
  3. 检查安装路径:
powershell
where.exe fnm

执行策略错误

如果遇到执行策略错误:

powershell
# 允许运行脚本
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

环境变量不生效

确保 PowerShell 配置文件正确加载:

powershell
# 检查配置文件路径
$PROFILE

# 检查配置文件内容
Get-Content $PROFILE

# 手动重新加载
. $PROFILE

WSL 中使用 fnm

如果你在 WSL 中使用 fnm:

bash
# 在 WSL 中安装
curl -fsSL https://fnm.vercel.app/install | bash

# 配置 Bash
echo 'eval "$(fnm env --use-on-cd)"' >> ~/.bashrc
source ~/.bashrc

下一步

安装完成后,你可以:

相关链接