Appearance
npm 性能优化
npm性能优化对于提高开发效率和构建速度至关重要。本章将详细介绍如何优化npm的安装速度、依赖管理、缓存策略等方面,以提升整体开发体验。
安装性能优化
npm配置优化
bash
# 设置并发连接数
npm config set maxsockets 50
# 设置重试次数和超时时间
npm config set fetch-retry-mintimeout 10000
npm config set fetch-retry-maxtimeout 60000
npm config set fetch-retries 3
# 启用进度条和日志
npm config set progress true
npm config set loglevel warn
# 设置缓存相关配置
npm config set cache-max 1073741824 # 1GB
npm config set cache-min 600000 # 10分钟
使用更快的注册表
bash
# 使用淘宝镜像(中国用户)
npm config set registry https://registry.npmmirror.com/
# 临时使用镜像安装
npm install --registry https://registry.npmmirror.com/
# 使用nrm管理镜像源
npm install -g nrm
nrm ls
nrm use taobao
nrm test
网络优化
bash
# 配置代理(如果在企业网络中)
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
# 设置CA证书
npm config set cafile /path/to/ca-certificates.crt
# 禁用SSL验证(仅在必要时,不推荐)
npm config set strict-ssl false
缓存优化
缓存管理
bash
# 查看缓存目录
npm config get cache
# 查看缓存统计
npm cache verify
# 查看缓存大小
du -sh $(npm config get cache)
# 清理缓存
npm cache clean --force
# 重新验证缓存
npm cache verify
缓存策略
bash
# 离线安装(优先使用缓存)
npm install --prefer-offline
# 在CI环境中禁用缓存
npm install --no-save --no-audit
# 使用缓存但检查更新
npm install --prefer-online
依赖优化
依赖树扁平化
npm自动进行依赖扁平化,但可以进一步优化:
bash
# 查看依赖树结构
npm ls --depth=0
npm ls --depth=1
# 检查重复依赖
npm ls | grep -c "node_modules"
依赖分析
bash
# 检查未使用的依赖
npx depcheck
# 检查过时的包
npm outdated
# 检查包大小
npx bundlephobia-cli package-name
# 分析依赖图
npx madge --image deps.svg --extensions js,ts src/
依赖精简
json
{
"scripts": {
"optimize-deps": "npx depcheck && npx npm-check",
"remove-unused": "npx npkill" // 交互式删除未使用依赖
}
}
安装策略
生产环境安装
bash
# 生产环境安装(跳过devDependencies)
npm install --production
# 使用npm ci进行可重现构建(推荐用于生产)
npm ci
# 在Docker中优化安装
RUN npm ci --only=production --no-optional
并行安装
bash
# 使用npm 7+的并行安装(默认启用)
npm install
# 使用第三方工具并行安装
npm install -g npm-check-updates
ncu -u
npm install
工作区性能
工作区安装优化
bash
# 在工作区中并行安装
npm install --workspaces
# 在特定工作区安装
npm install package-name --workspace=frontend
# 在所有工作区运行脚本
npm run build --workspaces --if-present
工作区缓存
json
{
"name": "my-workspace-project",
"private": true,
"workspaces": [
"packages/*"
],
"scripts": {
"build": "npm run build --workspaces",
"test": "npm run test --workspaces",
"install:fast": "npm ci --no-audit --no-fund"
}
}
CI/CD优化
持续集成优化
yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x, 18.x]
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Cache node modules
id: cache-nodemodules
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
- name: Install dependencies
if: steps.cache-nodemodules.outputs.cache-hit != 'true'
run: npm ci --no-audit --no-fund
env:
CI: true
- name: Run tests
run: npm test
Docker优化
text
# Dockerfile
FROM node:18-alpine
WORKDIR /app
# 复制package文件
COPY package*.json ./
# 安装依赖(利用Docker缓存层)
RUN npm ci --only=production --no-audit --no-fund \
&& npm cache clean --force
# 复制应用代码
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
包管理器比较
npm vs yarn vs pnpm
bash
# npm特点
# - 速度快(npm 7+)
# - 内置于Node.js
# - 工作区支持良好
npm install
# yarn特点
# - 锁定版本严格
# - 并行安装快
npm install -g yarn
yarn install
# pnpm特点
# - 磁盘空间效率高
# - 符号链接依赖
npm install -g pnpm
pnpm install
性能基准测试
bash
# 测试不同包管理器性能
npm install -g benchmark-cli
# 创建基准测试脚本
cat > benchmark.sh << 'EOF'
#!/bin/bash
echo "Testing npm..."
time npm install
echo "Testing yarn..."
time yarn install
echo "Testing pnpm..."
time pnpm install
EOF
chmod +x benchmark.sh
./benchmark.sh
高级优化技巧
使用npx优化
bash
# 使用npx运行一次性工具
npx create-react-app my-app
npx serve .
npx http-server
# npx会缓存包,后续运行更快
npx some-cli-tool
预构建依赖
json
{
"scripts": {
"prebuild": "npm run prebuild-deps",
"prebuild-deps": "node scripts/prebuild-deps.js",
"build-cache": "npm run build && npm run cache-artifacts"
}
}
依赖预拉取
bash
# 预拉取常用包
npm install -g create-react-app
npm install -g @vue/cli
npm install -g express-generator
# 使用缓存安装
npm install --prefer-offline
监控和测量
性能监控
bash
# 安装性能监控工具
npm install -g clinic
npm install -g 0x
# 使用clinic分析性能
clinic doctor -- node app.js
# 使用0x分析CPU性能
0x -- node app.js
安装时间测量
bash
# 测量安装时间
time npm install
# 使用自定义脚本测量
cat > measure-install.sh << 'EOF'
#!/bin/bash
START=$(date +%s.%N)
npm install
END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc)
echo "Installation took $DIFF seconds"
EOF
chmod +x measure-install.sh
./measure-install.sh
故障排除
常见性能问题
bash
# 问题:安装速度慢
# 解决:更换镜像源
npm config set registry https://registry.npmmirror.com/
# 问题:内存不足
# 解决:增加Node.js内存限制
export NODE_OPTIONS="--max-old-space-size=4096"
npm install
# 问题:磁盘空间不足
# 解决:清理缓存
npm cache clean --force
调试性能问题
bash
# 详细日志
npm install --verbose
# 显示进度
npm install --progress
# 禁用进度条(有时可以提高性能)
npm config set progress false
最佳实践
项目级优化
json
{
"name": "optimized-project",
"scripts": {
"preinstall": "node scripts/check-env.js",
"postinstall": "npm run build || exit 0",
"ci": "npm ci --no-audit --no-fund",
"install:fast": "npm install --prefer-offline --no-audit --no-fund",
"perf:check": "npx depcheck && npm ls --depth=0"
},
"engines": {
"node": ">=16.0.0",
"npm": ">=8.0.0"
},
"volta": {
"node": "18.12.1"
}
}
团队协作优化
bash
# 共享配置
# 创建.npmrc文件加入版本控制
echo "registry=https://registry.npmmirror.com/" > .npmrc
echo "audit=false" >> .npmrc
echo "fund=false" >> .npmrc
# 使用.editorconfig保持一致性
cat > .editorconfig << 'EOF'
root = true
[*.json]
indent_style = space
indent_size = 2
EOF
通过实施这些性能优化策略,您可以显著提高npm的工作效率,减少等待时间,从而提升整体开发体验。