📜  依赖关系、devDependencies 和 peerDependencies 之间的区别

📅  最后修改于: 2022-05-13 01:56:24.023000             🧑  作者: Mango

依赖关系、devDependencies 和 peerDependencies 之间的区别

简介:在每个 Web 应用程序项目中,我们都有一个名为 package.json 的文件。该文件包含有关项目的所有相关数据,即元数据。从所有用于所有版本号的依赖项开始,文件中都存在。这样,它们是在这个文件中找到的三种依赖关系。它们是依赖项、开发依赖项和对等依赖项。

运行以下命令从项目的根目录初始化项目:

npm init -y

Dependencies:在 package.json 文件中,有一个名为dependencies的对象,它由项目中使用的所有包及其版本号组成。因此,每当您安装项目中所需的任何库时,您都可以在依赖项对象中找到它。

句法:

npm install 

示例:使用以下命令在项目中安装用于格式化时间的 moment 模块:

npm install moment

安装模块后,如果您导航到 package.json 文件,那么您可以在依赖项对象中找到其版本的时刻,如下所示:

Dev Dependencies:在 package.json 文件中,有一个名为dev Dependencies的对象,它包含项目在其开发阶段而不是在生产或测试环境中使用的所有包及其版本号。因此,每当您想安装仅在开发阶段才需要的任何库时,您都可以在 dev Dependencies 对象中找到它。

使用以下命令在您的项目中添加更多开发依赖项:

npm install  --save-dev

示例:安装我们只想在开发阶段而不是在项目的生产或测试阶段使用的引导模块,使用以下命令:

npm install bootstrap --save-dev

下载完成后,如果你导航到 package.json 文件,你可以在 dev Dependencies 对象中找到引导程序及其版本,如下所示:

Peer Dependencies:在 package.json 文件中,有一个名为peerDependencies的对象,它包含项目中或下载者完全需要的所有包,版本号也应该相同。这就是它们被命名为 peerDependencies 的原因。最好的例子是“react”,它在每个项目中都很常见,以类似方式运行。

注意:这些依赖项不会自动安装。每当存在对等依赖项时,npm 都会发出警告消息,并且这些依赖项与上面讨论的依赖项相比是不同的。

下表总结了依赖关系、开发依赖关系和对等依赖关系。

DependenciesdevDependenciespeerDependencies
A dependency is a library that a project needs to function effectively.DevDependencies are the packages a developer needs during development. A peer dependency specifies that our package is compatible with a particular version of an npm package. 
If a package doesn’t already exist in the node_modules directory, then it is automatically added. As you install a package, npm will automatically install the dev dependencies.peerDependencies are not automatically installed. You need to manually modify your package.json file in order to add a Peer Dependency.
These are the libraries you need when you run your code.These dependencies may be needed at some point during the development process, but not during execution. Peer dependencies are only encountered when you publish your own package, that is, when you develop code that will be used by other programs. 
Included in the final code bundle. Included in the final code bundle . Can be included only when you are publishing your own package. 

Dependencies can be added to your project by running :

npm install 

Dev dependencies can be added to your project by running :

npm install  --save-dev
Change the package.json file manually.