Skip to content

使用 fnm 安裝 npm

npm(Node Package Manager)隨 Node.js 一起安裝。本指南介紹如何通過 fnm 管理 npm。

npm 與 fnm 的關系

當你使用 fnm 安裝 Node.js 時,npm 會自動包含在內:

bash
# 安裝 Node.js(自動包含 npm)
fnm install 20

# 驗證 npm 版本
npm --version

查看 npm 版本

bash
# 查看當前 npm 版本
npm --version

# 查看 Node.js 和 npm 版本
node --version
npm --version

不同 Node.js 版本對應不同的 npm 版本:

Node.jsnpm
20.x10.x
18.x9.x
16.x8.x

升級 npm

使用 npm 自升級

bash
# 升級到最新版本
npm install -g npm@latest

# 升級到指定版本
npm install -g npm@10.2.0

切換 Node.js 版本

切換 Node.js 版本會同時切換 npm 版本:

bash
# 切換到 Node.js 20
fnm use 20
npm --version  # 輸出: 10.x.x

# 切換到 Node.js 18
fnm use 18
npm --version  # 輸出: 9.x.x

npm 全局包管理

查看全局安裝路徑

bash
npm config get prefix

全局包位置

fnm 管理的 Node.js 全局包位於:

~/.fnm/node-versions/<version>/installation/lib/node_modules

安裝全局包

bash
# 安裝全局包
npm install -g pnpm
npm install -g yarn
npm install -g typescript

# 查看全局包
npm list -g --depth=0

使用 Corepack

Corepack 是 Node.js 的包管理器管理器,可以管理 npm、yarn 和 pnpm:

啟用 Corepack

bash
# 安裝 Node.js 時啟用 Corepack
fnm install 20 --corepack-enabled

# 或設置環境變量
export FNM_COREPACK_ENABLED=true
fnm install 20

使用 Corepack

bash
# 啟用 Corepack
corepack enable

# 使用指定版本的 yarn
corepack prepare yarn@stable --activate

# 使用指定版本的 pnpm
corepack prepare pnpm@latest --activate

npm 配置

配置鏡像

bash
# 設置 npm 鏡像
npm config set registry https://registry.npmmirror.com

# 查看當前配置
npm config list

# 恢復默認鏡像
npm config set registry https://registry.npmjs.org

常用鏡像

鏡像源地址
npm 官方https://registry.npmjs.org
npmmirrorhttps://registry.npmmirror.com
騰訊雲https://mirrors.cloud.tencent.com/npm/

多版本 npm 管理

由於 npm 隨 Node.js 一起安裝,管理多個 npm 版本的最佳方式是:

方法 1:切換 Node.js 版本

bash
# 安裝多個 Node.js 版本
fnm install 20
fnm install 18

# 切換版本
fnm use 20  # npm 10.x
fnm use 18  # npm 9.x

方法 2:獨立升級 npm

bash
# 在當前 Node.js 版本中升級 npm
npm install -g npm@latest

常見問題

npm 命令找不到

bash
# 確認 Node.js 已安裝
fnm list

# 確認當前使用的版本
fnm current

# 重新安裝 Node.js
fnm install 20 --use

全局包安裝失敗

bash
# 清除 npm 緩存
npm cache clean --force

# 檢查權限
ls -la ~/.fnm/node-versions/

# 重新安裝
npm install -g <package>

npm 版本不匹配

bash
# 檢查 Node.js 版本
fnm current

# 重置 npm 到默認版本
fnm uninstall <version>
fnm install <version>

最佳實踐

1. 使用 package.json 的 engines

在項目中指定 Node.js 和 npm 版本:

json
{
  "engines": {
    "node": ">=18.0.0",
    "npm": ">=9.0.0"
  }
}

2. 使用 .npmrc 文件

在項目中創建 .npmrc 文件:

registry=https://registry.npmmirror.com
save-exact=true

3. 鎖定包管理器

使用 packageManager 字段:

json
{
  "packageManager": "npm@10.2.0"
}

相關鏈接