npm – dependencies, devDependencies and peerDependencies

Imagine you’re building the next big thing. npm is like a magic box that gives you extra superpowers, packages, to make your thing easy to build.

So you rely on things, packages that other people have created. How can you tell the system that you want to use them and when they are necessary? How does it know which packages need to be distributed along with your code and which ones you only need during development?

That’s where dependencies come into play …

Dependencies in package.json

To tell npm which packages your project depends on, you must list them as dependencies or devDependencies. And sometimes you need to list them as peerDependencies. But which? When?

dependencies

These are packages your project requires to run properly in production. They are installed and bundled into your final code. They are essential for the app or site to function when deployed.

devDependencies

These are packages that are only needed during development. For example, for building, testing, or linting your code. They are not included in the production build. So you save space and keep things efficient.

peerDependencies

These specify packages that your project expects to be provided by the host environment or another dependency, rather than installing its own version. This avoids conflicts and duplication, assuming the peer is already there at a compatible version.

Example

The Groups plugin for WordPress uses a package.json for the blocks it provides.

  • It relies on the @wordpress/scripts package during development.
  • It requires the packages @wordpress/data, classnames and react-select.
  • It requires that the react package is provided by the host.
...
"devDependencies": {
	"@wordpress/scripts": "^25.1.0"
},
"dependencies": {
	"@wordpress/data": "^8.1.0",
	"classnames": "^2.3.1",
	"react-select": "^5.0.0"
},
"peerDependencies": {
	"react" : "^18.0.0"
},
...

The above is an excerpt from the plugin’s package.json used to build and distribute its blocks. The dependencies outlined above are reflected there.

Resources


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *