What are peer dependencies in a Node module?
A simple explanation of the peerDependencies field in the package.json file
In some package.json files, you might see a few lines like this:
{
//...
"peerDependencies": {
"libraryName": "1.x"
}
}
You might have already seen dependencies and devDependencies, but not peerDependencies.
dependencies are the packages your project depends on.
devDependencies are the packages that are needed during the development phase. Say a testing framework like Jest or other utilities like Babel or ESLint.
In both cases, when you install a package, its dependencies and devDependencies are automatically installed by npm.
peerDependencies are different. They are not automatically installed.
When a dependency is listed in a package as a peerDependency, it is not automatically installed. Instead, the code that includes the package must include it as its dependency.
npm will warn you if you run npm install and it does not find this dependency.
Example: let’s say package a includes dependency b:
a/package.json
{
//...
"dependencies": {
"b": "1.x"
}
}
Package b in turn wants package c as a peerDependency:
b/package.json
{
//...
"peerDependencies": {
"c": "1.x"
}
}
In package A, we must therefore add c as a dependency, otherwise when you install package b, npm will give you a warning (and the code will likely fail at runtime):
a/package.json
{
//...
"dependencies": {
"b": "1.x",
"c": "1.x"
}
}
The versions must be compatible, so if a peerDependency is listed as 2.x, you can’t install 1.x or another version. It all follows semantic versioning.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.