0%

peerDependencies介绍及简析

peerDependencies是npm一个比较早的概念,以前一直没有注意过因为它主要是跟插件的开发相关,直到最近负责做一些插件开发,才接触到这个东西。

我们对dependencies和devDependencies应该都很熟悉了,但是除了它们两个意外,package.json里还可以配置一个叫peerDependencies的配置。我们在NPM3的安装中有时候会有这样的提示:

1
2
3
npm WARN peerDependencies The peer dependency mocha@>=1.x.x included from grunt-mocha-istanbul will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.

这个警告的意思是grunt-mocha-istanbul插件设置了对mocha@>=1.x.x的peerDependencies,但是npm 3+不再自动安装peerDependencies,应用需要明确的依赖它(添加到 package.json 的 dependencies 等地方)。

这点要说明,在npm1和2的版本中,peerDependencies是会被自动安装的,但是在3的版本中只会有警告。

设置peerDependencies的方法很简单:

1
2
3
4
5
6
7
{
"name": "yourproject",
"version": "1.3.5",
"peerDependencies": {
"mocha": "1.x"
}
}

npm文档中对peerDependencies的介绍是:

In some cases, you want to express the compatibility of your package with a host tool or library, while not necessarily doing a require of this host. This is usually referred to as a plugin. Notably, your module may be exposing a specific interface, expected and specified by the host documentation.

大概的意思就是:通常是在插件开发的场景下,你的插件需要某些依赖的支持,但是你又没必要去安装,因为插件的宿主会去安装这些依赖,你就可以用peerDependencies去声明一下需要依赖的插件和版本,如果出问题npm就会有警告来提醒使用者去解决版本冲突问题。


参考:
https://docs.npmjs.com/files/package.json#peerdependencies
https://github.com/hongfanqie/peer-dependencies