Understanding peerDependencies
·
2 min read
·
321
Words
·
-Views
-Comments
Besides dependency and devDependency in package.json, there’s also peerDependency. Let’s resolve a real-world error to understand how it works.
Error Message
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: a@0.0.1-beta
npm ERR! Found: ssh2@1.15.0
npm ERR! node_modules/ssh2
npm ERR! ssh2@"1.15.0" from the root project
npm ERR! ssh2@"^1.12.0" from ssh2-sftp-client@9.1.0
npm ERR! node_modules/ssh2-sftp-client
npm ERR! ssh2-sftp-client@"^9.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer ssh2@"1.16.0" from a@0.0.1-beta
npm ERR! packages/a
npm ERR! a@0.0.1-beta
npm ERR! node_modules/a
npm ERR! workspace packages/a from the root project
npm ERR!
npm ERR! Conflicting peer dependency: ssh2@1.16.0
npm ERR! node_modules/ssh2
npm ERR! peer ssh2@"1.16.0" from a@0.0.1-beta
npm ERR! packages/a
npm ERR! a@0.0.1-beta
npm ERR! node_modules/a
npm ERR! workspace packages/a from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! /Users/alanhe/.npm/_logs/2025-01-02T02_53_13_141Z-eresolve-report.txt
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/alanhe/.npm/_logs/2025-01-02T02_53_13_141Z-debug-0.log
Error Analysis
The project’s direct dependency pins ssh2 at version 1.15.0, while package a lists ssh2@1.16.0 in its peerDependency field.
Because peerDependencies declare which version the consuming project must install, npm expects us to have ssh2@1.16.0. With 1.15.0 installed, it throws a conflict.
Solution
Once you know the root cause, the fix is simple: upgrade ssh2 in the main project to the required version.
Summary
- PeerDependencies let a package specify the acceptable version range of another dependency in the consuming project. When the consuming project also depends on it, that version must satisfy the peer constraint.
- Declaring something in peerDependencies doesn’t install it automatically if the main project doesn’t list it in dependencies. In current npm versions (such as v9), it only gets installed when another package depends on it.