Peer Dependencies (`peerDependencies`)
Guide to peerDependencies in package.json, plugin architectures, peerDependenciesMeta optional peers, and resolving conflicting peer dependencies.
The peerDependencies field in package.json specifies that your package requires a specific version of a host package, but expects the consumer's root application to provide and install it.
Why Peer Dependencies Exist (The Plugin Problem)
If you are authoring a React component library (e.g. my-button-ui), you need react to compile and run.
- If you put
reactintodependencies, npm could install a second copy of React insidenode_modules/my-button-ui/node_modules/react. - Having two copies of React in the same application breaks React Hooks (
Invalid hook callruntime crash!).
By declaring react as a peer dependency, you guarantee that my-button-ui shares the exact single instance of React installed by the root application:
{
"name": "my-button-ui",
"version": "1.0.0",
"peerDependencies": {
"react": ">=18.0.0 <20.0.0",
"react-dom": ">=18.0.0 <20.0.0"
}
}Optional Peer Dependencies (peerDependenciesMeta)
If your package works fine without a peer, but enhances features if it is present:
{
"peerDependencies": {
"redis": "^4.0.0"
},
"peerDependenciesMeta": {
"redis": {
"optional": true
}
}
}Resolving Peer Dependency Conflicts (npm 7+)
In npm 7+, npm attempts to automatically install missing peer dependencies. If there is a version mismatch, npm throws an ERESOLVE unable to resolve dependency tree error.
Fixes:
- Align versions: Upgrade or downgrade packages to compatible ranges (Best practice).
--legacy-peer-deps: Instructs npm to ignore peer dependency conflicts during install:npm install --legacy-peer-deps- Overriding versions: Use the
overrides(npm) orpnpm.overrides(pnpm) field in rootpackage.json.
Related Guides
Development Dependencies (`devDependencies`)
Guide to devDependencies in package.json, why separating dev tools matters, how production builders prune devDependencies, and install commands.
npm Scripts & Task Automation
Complete guide to defining and running scripts in package.json, pre/post lifecycle hooks, passing arguments, environment variables, and parallel task execution.