Migrating a project from npm or Yarn to pnpm requires attention to the following steps and issues:
Migration Steps:
- Install pnpm
bash# Install using npm npm install -g pnpm # Install using standalone script curl -fsSL https://get.pnpm.io/install.sh | sh - # Using Homebrew (macOS) brew install pnpm
- Clean Old Dependencies
bash# Remove node_modules rm -rf node_modules # Remove old lock files rm package-lock.json # npm rm yarn.lock # Yarn
- Import Lock File (Optional)
bash# pnpm can import from npm/yarn lock files pnpm import # This generates pnpm-lock.yaml
- Install Dependencies
bashpnpm install
Handling Common Issues:
- Phantom Dependencies Issue
javascript// ❌ Could run before migration (phantom dependency) const lodash = require('lodash'); // Not declared in package.json // ✅ Need to declare explicitly after migration pnpm add lodash
- Peer Dependencies Issue
bash# pnpm checks peer dependencies more strictly # May encounter peer dependency errors # Solution 1: Install missing peer dependencies pnpm add react react-dom # Solution 2: Use overrides # package.json { "pnpm": { "overrides": { "react": "^18.0.0" } } }
- shamefully-hoist Configuration
bash# If project depends on flat node_modules structure # .npmrc shamefully-hoist=true # This creates a flat structure similar to npm # But loses pnpm's strict dependency management advantages
Configuration File Migration:
bash# .npmrc configuration shamefully-hoist=true # Flat mode strict-peer-dependencies=false # Non-strict peer dependencies check auto-install-peers=true # Auto install peer dependencies
package.json Adjustment:
json{ "scripts": { "preinstall": "npx only-allow pnpm" // Force use pnpm }, "engines": { "pnpm": ">=8.0.0" } }
CI/CD Configuration Update:
yaml# GitHub Actions - name: Setup pnpm uses: pnpm/action-setup@v2 with: version: 8 - name: Install dependencies run: pnpm install --frozen-lockfile
Monorepo Migration:
yaml# Create pnpm-workspace.yaml packages: - 'packages/*' - 'apps/*'
json// Update inter-package dependency references { "dependencies": { "@my-org/utils": "workspace:*" // Use workspace protocol } }
Migration Checklist:
bash# 1. Check phantom dependencies pnpm ls --depth=0 # 2. Check peer dependencies pnpm install --strict-peer-dependencies # 3. Run tests pnpm test # 4. Build project pnpm build # 5. Check script commands pnpm run <script>
Rollback Plan:
bash# If migration fails, can rollback rm pnpm-lock.yaml rm -rf node_modules npm install # or yarn install
Advantages After Migration:
- 2-3x faster installation
- 50-70% disk space savings
- Stricter dependency management
- Better monorepo support