在 mac 上有很多种方式安装npm。但是我最推荐的还是通过 nvm 的方式来安装 npm,因为前端开发中,常常需要切换不同过的 npm 版本,对于一些比较老的项目,用最新的 npm 就是会跑不起来。
方案一
其中比较简单的方式就是去官网下载安装包,点击安装就行。
可以在官网中点击是要安装LTS(长期支持版本),也可以下载最新版本 当前事件 Node.js v20.18.0 是 LTS 版本,Node.js v22.9.0 是最新版本
方案二
通过homebrew的方式安装。
brew install node
node -v
v22.9.0
安装的是最新的版本
方案三
通过 nvm 安装
Node.js — Download Node.js® (nodejs.org)
# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
# download and install Node.js (you may need to restart the terminal)
nvm install 20
# verifies the right Node.js version is in the environment
node -v # should print `v20.18.0`
# verifies the right npm version is in the environment
npm -v # should print `10.8.2`
这种方式很可能会失败,因为网络的问题。结合之前文章的安装的 homebrew,采用brew 命令来安装。
brew install nvm
但是安装之后并不意味就能直接使用 nvm 命令了。
还需要配置一下
打开终端的配置文件(如.bash_profile或.zshrc)。您可以使用nano、vim或其他文本编辑器进行编辑。
vi ~/.bash_profile
export NVM_DIR=”$HOME/.nvm”
[ -s “$NVM_DIR/nvm.sh” ] && . “$NVM_DIR/nvm.sh” # This loads nvm
[ -s “$NVM_DIR/bash_completion” ] && . “$NVM_DIR/bash_completion” # This loads nvm bash_completion
在终端中执行以下命令,使配置的环境变量生效:
source ~/.bash_profile
或者,如果您使用的是zsh,则执行:
source ~/.zshrc
关于配置文件,我其实有一个建议,就是可以用软链接的方式比如你修改的.zshrc , 但是也想同步修改.base_profile 那么
ln -s .zshrc .bash_profile
nvm 的一些命令
- 使用
nvm ls-remote命令查看可用的Node.js版本列表。 - 使用
nvm install <version>命令安装特定版本的Node.js。例如,要安装Node.js 14.17.0,可以执行nvm install 14.17.0。 - 使用
nvm use <version>命令切换到已安装的特定版本的Node.js。例如,要切换到Node.js 14.17.0,可以执行nvm use 14.17.0。 - 使用
nvm current命令查看当前正在使用的Node.js版本。
npm 镜像源切换
安装完 npm 后,会遇到一个问题,就是一些 依赖下载不下来,下载不下来的原因还是因为网络的原因。
1. 临时使用某个镜像源
npm install --registry=https://registry.npmmirror.com
2. 永久配置npm镜像源:
# 设置镜像源
npm config set registry https://registry.npmmirror.com
# 查看当前使用的镜像地址
npm config get registry
# 淘宝镜像源
https://registry.npmmirror.com
https://registry.npm.taobao.org # 这个已经不能使用了
# 腾讯云镜像源
http://mirrors.cloud.tencent.com/npm/
# 华为云镜像源
https://mirrors.huaweicloud.com/repository/npm/
# 官方默认全局镜像
https://registry.npmjs.org
3. 给项目单独配置npm镜像源
项目根目录的 .npmrc 的配置,优先级最高,且随着项目一起,可以免去因不同开发者的电脑的环境配置不同而导致的依赖下载异常的问题;实际开发中也推荐在根目录下配置一份,可以给每个项目配置不同的镜像,项目之间的配置互不影响。
#### 配置 npm 的默认镜像源为淘宝镜像源
registry = "https://registry.npmmirror.com"
使用nrm工具管理和切换镜像源
npm install -g nrm
nrm ls # 列出所有可用的镜像源
nrm use taobao # 切换到淘宝镜像源