In every Node.js based web application project, we have a file called package.json. This file contains all relevant data about the project, i.e. metadata. Three different dependency types can be defined in package.json: dependency, devDependency and Peer Dependency.
This article outlines some common usage scenarios for Peer Dependency.
- Babel plugins: In the development of Babel plugins, Babel itself needs to be defined as a peer dependency.
- Express middleware packages: This is a typical NPM module development scenario that requires the use of peer-to-peer dependencies. The developer of the middleware package wants to declare express as a dependency, not a
硬
dependency. Otherwise, each installation of each middleware package will install the entire express under the node_modules folder. - If you are building a micro frontend, you need to determine which dependencies are external (so they won't be bundled) and which are not. Peer-to-peer dependencies might be an optional solution to this problem.
the whole frame. - Bit Components: If you are writing and publishing front-end components, such as when sharing React components on Bit. In this case, React can be declared as a peer dependency of the component, with the semantics that the developer expects the host project to have the correct version specified by the peer Dependency.
See a practical example, a button that can be clicked repeatedly:
After installation, observe the peer Dependency defined in its package.json:
In this package.json file, this package does not define any direct dependencies, even though it works on top of React. We make sure things like React and React-dom are required, just not installed. This is the semantics that NPM's peer-to-peer dependencies are meant to express.
Given the flexibility of the plugin-based architecture, many libraries are taking advantage of it, allowing developers to organically extend the functionality of the framework according to their needs. This makes it necessary for any developer interested in developing new features for these frameworks to master the proper usage of Peer Dependency.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。