使用 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.js | npm |
|---|---|
| 20.x | 10.x |
| 18.x | 9.x |
| 16.x | 8.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.xnpm 全局包管理
查看全局安装路径
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 --activatenpm 配置
配置镜像
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 |
| npmmirror | https://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=true3. 锁定包管理器
使用 packageManager 字段:
json
{
"packageManager": "npm@10.2.0"
}相关链接
- 安装 Node.js - 安装 Node.js
- 版本管理 - 版本管理指南
- 命令参考 - 所有命令详解