なっく日報

技術やら生活やらのメモ

package.jsonのpeerDependenciesについて調べた

諸事情で、peerDependenciesの挙動について調べる機会があったのでそのメモを。

どういう場合に使うのか?

https://docs.npmjs.com/files/package.json#peerdependenciesdocs.npmjs.com

なんやかんやで、結局公式ドキュメントが一番参考になりました。

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.

要は、ESLintとかGruntのプラグインで、特定のバージョンのESLintやGruntに依存しているようなパターンで使うと。

自分の場合

  • ESLintの共有設定(eslint-config-xxx)を作っていて
  • その中でプラグインextendsしていて
  • npm linkで動作確認している途中で

「あ、これはpeerDependenciesが必要だな」と思いました。

おまえは何を言っているんだ感満載ですが、

https://github.com/airbnb/javascript/blob/8b58d8770cc1dcb3a2e4a7b7be94ea84d4dc3c4c/packages/eslint-config-airbnb/package.json#L48

このpackage.jsonを読めば、雰囲気が伝わるかもしれません。

指定するとどういう挙動になるのか?

これまた公式に書いています。

npmのv3以降で挙動が変わったそう。

NOTE: npm versions 1 and 2 will automatically install peerDependencies if they are not explicitly depended upon higher in the dependency tree. In the next major version of npm (npm@3), this will no longer be the case. You will receive a warning that the peerDependency is not installed instead.

ローカルにeslintとeslint-plugin-reactがインストールされていない状態でnpm i eslint-config-airbnbしてみたところ

npm v2の場合

警告が出る&勝手にpeerDependenciesに書いてあるモジュールがインストールされる

npm WARN peerDependencies The peer dependency eslint@^1.0.0 included from eslint-config-airbnb 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.
npm WARN peerDependencies The peer dependency eslint-plugin-react@^3.16.1 included from eslint-config-airbnb 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.
eslint-plugin-react@3.16.1 node_modules/eslint-plugin-react

eslint@1.10.3 node_modules/eslint
〜(中略)〜

eslint-config-airbnb@5.0.1 node_modules/eslint-config-airbnb

npm v3の場合

警告が出るのみ

npm WARN EPEERINVALID eslint-config-airbnb@5.0.1 requires a peer of eslint@^1.0.0 but none was installed.
npm WARN EPEERINVALID eslint-config-airbnb@5.0.1 requires a peer of eslint-plugin-react@^3.16.1 but none was installed.

警告が出たら、npm i -D eslint@^1.0.0 eslint-plugin-react@^3.16.1してあげるのが正しい解決方法のようです。

気をつける点

Assuming the host complies with semver, only changes in the host package's major version will break your plugin. Thus, if you've worked with every 1.x version of the host package, use "^1.0" or "1.x" to express this. If you depend on features introduced in 1.5.2, use ">= 1.5.2 < 2".

極力広いバージョンをカバーするような書き方をしなさいとのこと。 v1系をサポートしているなら ^1.0 or 1.x1.5.2の機能に依存しているなら、>= 1.5.2 < 2 のように。