为什么要在npm中使用对等依赖性插件?

node.js Node.js

小胖

2020-03-23

例如,为什么Grunt插件将其对grunt的依赖关系定义为“ 对等依赖关系 ”?

为什么插件在grunt-plug / node_modules中不能仅仅将Grunt作为其依赖

对等依赖项在此处进行了描述:https : //nodejs.org/en/blog/npm/peer-dependencies/

但是我真的不明白。

目前,我正在使用AppGyver Steroids,它使用Grunt任务将我的源文件构建到/ dist /文件夹中,以便在本地设备上提供服务。我在npm上很新,很咕gr,所以我想完全理解发生了什么。

到目前为止,我得到了:

[rootfolder] /package.json告诉npm它依赖于grunt-steroidsnpm包进行开发:

  "devDependencies": {
    "grunt-steroids": "0.x"
  },

好的。[rootfolder]中运行npm install 可以检测依赖性,并在[rootfolder] / node_modules / grunt-steroids中安装grunt-steroids

Npm然后读取[rootfolder] /node_modules/grunt-steroids/package.json,以便它可以安装grunt-steroids自己的依赖项。

"devDependencies": {
    "grunt-contrib-nodeunit": "0.3.0",
    "grunt": "0.4.4"
  },
"dependencies": {
    "wrench": "1.5.4",
    "chalk": "0.3.0",
    "xml2js": "0.4.1",
    "lodash": "2.4.1"
  },
"peerDependencies": {
    "grunt": "0.4.4",
    "grunt-contrib-copy": "0.5.0",
    "grunt-contrib-clean": "0.5.0",
    "grunt-contrib-concat": "0.4.0",
    "grunt-contrib-coffee": "0.10.1",
    "grunt-contrib-sass": "0.7.3",
    "grunt-extend-config": "0.9.2"
  },

依赖 ”软件包安装在[rootfolder] / node_modules / grunt-steroids / node_modules中,这对我来说很合理。

未安装devDependencies ”,我确定这是由npm检测控制的,即我只是在尝试使用grunt-steroids而不是在上面进行开发。

但是然后我们有了“ peerDependencies ”。

这些安装在[rootfolder] / node_modules中,我不明白为什么会在[rootfolder] / node_modules / grunt-steroids / node_modules中安装而不是为什么,这样可以避免与其他grunt插件(或其他插件)发生冲突?

第2826篇《为什么要在npm中使用对等依赖性插件?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Stafan路易 2020.03.23

peerDependencies 用最简单的示例进行解释:

{
  "name": "myPackage",
  "dependencies": {
    "foo": "^4.0.0",
    "react": "^15.0.0"
  }
}


{
  "name": "foo"
  "peerDependencies": {
    "react": "^16.0.0"
  }
}

在myPackage中运行npm install会引发错误,因为它试图安装React版本^15.0.0AND foo并且仅与React兼容^16.0.0

没有安装peerDependencies。

Mandy村村 2020.03.23

我建议您先重新阅读该文章。这有点令人困惑,但是带有winston-mail的示例向您显示了答案:

例如,让我们假装在其对象winston-mail@0.2.3指定"winston": "0.5.x""dependencies"对象,因为这是对其进行测试的最新版本。作为应用程序开发人员,您需要最新和最棒的东西,因此您查找winston的最新版本winston-mail并将其放入package.json中,如下所示:

{
  "dependencies": {  
    "winston": "0.6.2",  
    "winston-mail": "0.2.3"  
  }  
}

但是现在,运行npm install会导致意外的依赖关系图

├── winston@0.6.2  
└─┬ winston-mail@0.2.3                
  └── winston@0.5.11

在这种情况下,可能有一个软件包的多个版本,这会引起一些问题。通过对等依赖关系,npm开发人员可以确保用户具有特定的模块(在根文件夹中)。但是您的观点是正确的,即描述软件包的一个特定版本会导致使用其他版本的其他软件包出现问题。如文章所述,此问题与npm开发人员有关

一条建议:与常规依赖不同,对等依赖要求应该宽松您不应将对等依赖项锁定到特定的补丁程序版本。

因此,开发人员应遵循semver定义peerDependencies。您应该在GitHub上打开grunt-steroids软件包的问题...

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android