What are peerDependencies in package.json?
peerDependencies declare packages your library needs but expects the host application to install, so only one shared copy exists. Plugins and UI libraries use them, for example a React component library requiring react.
Explain it simply
Imagine a phone case sold for a specific phone model. The case does not ship with a phone; it assumes you already own one. A peer dependency says the same: "I work with express 4, but you must bring your own express."
If a plugin listed express as a normal dependency, npm could install a second copy inside the plugin's folder. Two copies of the same library can cause strange bugs, especially for things that must be a single instance, like React or a framework's internal registry.
Example
{
"name": "express-fest-logger",
"version": "1.0.0",
"peerDependencies": {
"express": "^4.18.0"
}
}Behaviour:
- npm 7 and later install missing peer dependencies automatically, and warn or fail if the versions conflict.
- npm 6 only printed a warning, so older tutorials say you must install them yourself.
- Add the same package under
devDependenciesin the library too, so you can test it locally.
Apps rarely need peerDependencies themselves. It matters mainly when you publish a package for others.
What to say in the interview
"peerDependencies say the host project must provide a package, so the library shares one copy with the app. They are used by plugins and framework add-ons. Since npm 7 they are installed automatically."
Common mistakes
- Putting a framework like express in
dependenciesof a plugin and ending up with duplicate copies. - Ignoring
ERESOLVEpeer conflict errors by always passing--force.