npm安装时一直卡住的解决方法

npm install 卡住通常是由于网络问题或缓存问题导致的。以下是几种解决方法:

方法1:清理npm缓存

bash 复制代码
npm cache clean --force
npm install

方法2:删除node_modules和package-lock.json重新安装

bash 复制代码
rm -rf node_modules package-lock.json
npm install

(Windows PowerShell 中使用:)

powershell 复制代码
Remove-Item -Recurse -Force node_modules, package-lock.json
npm install

方法3:使用国内镜像源

bash 复制代码
# 临时使用淘宝镜像
npm install --registry https://registry.npmmirror.com

# 或者永久设置
npm config set registry https://registry.npmmirror.com

方法4:增加超时时间

bash 复制代码
npm install --timeout=60000

方法5:使用yarn替代npm

bash 复制代码
# 如果没有yarn,先安装
npm install -g yarn

# 然后使用yarn安装依赖
yarn install

方法6:检查网络和代理设置

如果你在使用代理,可能需要配置npm代理:

bash 复制代码
npm config set proxy http://your-proxy:port
npm config set https-proxy http://your-proxy:port

如果还是不行则继续分析

主要问题:淘宝镜像证书过期

旧的淘宝镜像 registry.npm.taobao.org 已经停用,需要更换为新的镜像:

bash 复制代码
# 更换为新的淘宝镜像
npm config set registry https://registry.npmmirror.com

完整解决步骤:

1. 更换镜像源

powershell 复制代码
npm config set registry https://registry.npmmirror.com

2. 解决文件占用问题

由于有文件被占用无法删除,需要:

powershell 复制代码
# 关闭所有可能占用文件的程序(VSCode、编辑器等)
# 然后强制删除
Remove-Item -Recurse -Force node_modules -ErrorAction SilentlyContinue
Remove-Item -Force package-lock.json -ErrorAction SilentlyContinue

如果还是删不掉,重启电脑后再删除。

3. 重新安装

powershell 复制代码
npm install

其他可用的镜像源:

bash 复制代码
# 官方源(较慢但稳定)
npm config set registry https://registry.npmjs.org

# 阿里云镜像(推荐)
npm config set registry https://registry.npmmirror.com

# 腾讯云镜像
npm config set registry https://mirrors.cloud.tencent.com/npm/

# 华为云镜像
npm config set registry https://repo.huaweicloud.com/repository/npm/

关于core-js警告

这只是一个警告,不影响安装。如果想解决,可以在项目完成后升级依赖:

bash 复制代码
npm update core-js

验证镜像源是否设置成功:

bash 复制代码
npm config get registry

应该显示新的镜像地址。

建议: 先更换镜像源,然后删除node_modules重新安装,这样应该就能解决问题了。

powershell 复制代码
Remove-Item -Recurse -Force node_modules
Remove-Item package-lock.json
powershell 复制代码
# Short version
rm -r -fo node_modules
rm package-lock.json
powershell 复制代码
rm -r -fo node_modules, package-lock.json
powershell 复制代码
npm install