What are npm peer dependencies?

Jan 20, 2024#npm#node

In the package.json file of a Node.js project, dependencies are classified into three main types: dependencies, devDependencies, and peerDependencies. Each serves a different purpose in managing project dependencies.

{
  "dependencies": {
    "express": "^4.17.1",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "mocha": "^9.0.0",
    "chai": "^4.3.4"
  },
    "peerDependencies": {
    "react": "^17.0.0"
  }
}

Section dependencies is used for listing the packages that your application needs to run in a production environment. These are dependencies that are necessary for the application to function as intended.

Section devDependencies is used for listing packages that are only needed during development or testing. These dependencies are not required for the production runtime but may be necessary for building, testing, or other development-related tasks.

Peer dependencies are a way to declare dependencies that a package expects to be present at a higher level in the dependency tree. Unlike regular dependencies, which are automatically installed in the node_modules folder of the dependent package, peer dependencies are not automatically installed.

Peer dependencies are useful when a package relies on a specific version of another package but does not want to include that package as part of its own installation. Instead, it expects the consumer of the package to install the peer dependency themselves.

Suppose you have a package A that has a peer dependency on package B:

// Package A's package.json
{
  "name": "package-a",
  "version": "1.0.0",
  "peerDependencies": {
    "package-b": "^2.0.0"
  }
}

In this example, package A declares that it expects package B to be present, and it requires version 2.0.0 or any compatible version. When a user installs package A, npm will not automatically install package B. Instead, the user must manually install package B in their project, making sure it meets the specified version requirements.

To install the peer dependencies manually, a user can run:

npm install package-b@^2.0.0

This approach allows for more flexibility in managing dependencies, especially in cases where multiple packages need to share a common dependency but don’t want to force a specific version on the user.