如何优化 npm 安装速度?

优化 npm install 速度的方法包括切换镜像源、使用更高效的包管理工具如 Yarn 或 pnpm,以及调整网络和缓存设置。

部署与运维 中等 npm 性能优化 NPM

要加速 npm install,可以使用以下策略:

  1. 切换国内镜像源
    • 设置淘宝镜像 (推荐高速稳定)
      npm config set registry https://registry.npmmirror.com
      
    • 单个包安装使用临时镜像
      npm install --registry=https://registry.npmmirror.com
      
  2. 使用高效的包管理工具替代
    • Yarn: Facebook 开发的提速工具
      npm install -g yarn
      yarn config set registry https://registry.npmmirror.com
      yarn install
      
    • pnpm: 节省磁盘并提升速度
      npm install -g pnpm
      pnpm config set registry https://registry.npmmirror.com
      pnpm install
      
    • cnpm: 淘宝镜像工具 (谨慎选择,避免潜在 bug)
      npm install -g cnpm --registry=https://registry.npmmirror.com
      cnpm install
      
  3. 优化安装参数
    • 跳过非必要依赖,只安装 dependencies
      npm install --production
      
    • 关闭进度条提升速度
      npm set progress=false
      
    • 禁用安全审计和资助提示
      npm install --no-audit --fund=false
      
  4. 管理网络与缓存
    • 设置并行下载增强连接数:
      npm config set maxsockets 10
      
    • 清理旧缓存强制优化
      npm cache clean --force
      
    • 使用离线模式复用缓存
      npm install --prefer-offline
      
  5. 高级网络设置
    • 若代理需求,设置环境变量
      export http_proxy=http://127.0.0.1:7890
      export https_proxy=http://127.0.0.1:7890
      
    • 配置 npm 代理直接连官方源
      npm config set proxy http://127.0.0.1:7890
      npm config set https-proxy http://127.0.0.1:7890
      
    • 确保文件设置持久性(创建 .npmrc 项目配置)

其他提示:

  • 优先使用 Yarn 或 pnpm(自带加速机制)。
  • --production 适用于生产环境,开发者需补装 devDependencies
  • 确保 npm 或 Node.js 版本更新以利用最新优化。