乐闻世界logo
搜索文章和话题

What are the differences between pnpm's overrides and resolutions and how to use them?

3月6日 23:39

pnpm provides powerful dependency override mechanisms, mainly through overrides and resolutions.

pnpm.overrides:

Used to force override dependency versions, regardless of what version the original dependency declares.

json
// package.json { "pnpm": { "overrides": { "lodash": "^4.17.21", "react": "^18.0.0" } } }

Usage Scenarios:

  1. Fix Security Vulnerabilities
json
{ "pnpm": { "overrides": { "minimist@<1.2.6": "^1.2.6" } } }
  1. Force Version Unification
json
{ "pnpm": { "overrides": { "typescript": "^5.0.0" } } }
  1. Replace Packages
json
{ "pnpm": { "overrides": { "node-sass": "sass" } } }

Path Overrides:

json
{ "pnpm": { "overrides": { "react": "$react", // Use project's version "webpack>lodash": "^4.17.21" // Only override webpack's lodash } } }

resolutions (Yarn Compatibility):

json
// package.json { "resolutions": { "lodash": "^4.17.21" } }

Comparison:

Featurepnpm.overridesresolutions
ScopeAll dependenciesAll dependencies
PriorityHighMedium
Yarn Compatible
Path Specification
Version Reference

Practical Example:

json
// Complex override scenario { "dependencies": { "react": "^18.0.0", "react-dom": "^18.0.0", "antd": "^5.0.0" }, "pnpm": { "overrides": { // Ensure all packages use same React version "react": "$react", "react-dom": "$react-dom", // Fix antd's dependency vulnerability "antd>rc-util": "^5.30.0", // Replace deprecated package "request": "axios" } } }

Verify Override Effect:

bash
# View actually installed version pnpm list react # View dependency tree pnpm list --depth=10 # View why this version is installed pnpm why lodash

Important Notes:

  1. Use Global Overrides Carefully
json
// ❌ Not recommended: Global override may cause incompatibility { "pnpm": { "overrides": { "react": "^18.0.0" } } } // ✅ Recommended: Path specification is more precise { "pnpm": { "overrides": { "some-package>react": "^18.0.0" } } }
  1. Update Lock File
bash
# Need to reinstall after modifying overrides pnpm install # Or force update pnpm install --force
标签:PNPM