Dependencies and devDependencies

Dependencies and devDependencies are common in development. Dependencies depend on packages that are installed in the deployment environment, such as Vue and React. DevDependencies are in-development dependencies, such as ESLint. So what are peerDependencies?

example

Let me start with an example. Open the Github project address of the Ant Design Component Library (ANTD), and you’ll find not only dependencies, devDependencies, and peerDependencies in package.json.

"PeerDependencies" : {" react ":" > = 16.9.0 ", "the react - dom" : "> = 16.9.0"},Copy the code

< span style = “box-sizing: border-box; color: RGB (51, 51, 51); line-height: 21px; font-size: 14px! Important; word-wrap: inherit! Important;”

Simply put, after declaring dependencies like this, the node_modules directory structure becomes:

├─ your-project ├─ ├─ react │ ├─ antd │ ├─ ├─ └Copy the code

Imagine if antD’s dependencies used the Dependencies statement

"Dependencies" : {" react ":" > = 16.9.0 ", "the react - dom" : "> = 16.9.0"}Copy the code

Then its node_modules directory structure becomes:

├ ─ ─ your - project │ └ ─ ─ node_modules │ ├ ─ ─ [email protected] │ ├ ─ ─ antd │ │ └ ─ ─ nodule_modules │ │ └ ─ ─ [email protected]Copy the code

This means that there will be two versions of React in the project, which may cause some problems. Generally, only one base library will be installed in a project and its version is fixed. When it needs to be upgraded, it will deal with compatibility problems to upgrade.

For antD, peerDependencies is a good choice. If the main project installs the appropriate Version of React, the component libraries can share this version of React without having to install another one, and there will be no compatibility problems between different versions.

Often used in plug-ins

PeerDependencies are often used in plug-in development

Plug-ins generally have the following features:

  • The premise for the plug-in to run correctly is that the core dependency library must be downloaded and installed first, and cannot be independently relied on and referenced from the core dependency library
  • In project practice, it is best to have the same version of the core dependency library under the same plug-in architecture

Use peerDependencies to meet these requirements:

  • If the user relies on a core library that satisfies the peerDependencies declaration, the declaration of peerDependencies is ignored
  • If the user does not rely on the core library, the library is installed in the root directory of the project as declared in peerDependencies
  • If the version that the user depends on is incompatible with the version that the plug-in depends on, an error is reported for the user to fix