LoginSignup
7
1

More than 1 year has passed since last update.

peerDependenciesMetaのoptionalとoptionalDependenciesの違いとは?

Last updated at Posted at 2022-06-10

package.jsonに設定する項目に、peerDependenciesMeta optional:trueと書かれているのを見て、optionalDependenciesとの違いが分からなかったので調べてみました。

もし間違いがありましたら、コメントか編集リクエストをお願いします

違い

このように書かれていました。

they're entirely different, albeit similar. optionalDependencies means, if the dep fails to install, don't fail the overarching install. peerDependenciesMeta allows you to provide extra information about peer deps, and marking one "optional" means "it's not an error if it's missing".

DeepL訳

似たようなものではありますが、まったく別のものです。optionalDependencies は、その dep がインストールに失敗しても、全体的なインストールを失敗させないことを意味します。peerDependenciesMeta は、仲間の dep に関する追加情報を提供することができ、optional とマークすることは、「それが欠けていてもエラーにはならない」ことを意味します。

とはいえ、これだけ見てもちょっと分からなかったので、それぞれがどのような時に使うのかを調べてみます。

optionalDependencies

If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the optionalDependencies object. This is a map of package name to version or url, just like the dependencies object. The difference is that build failures do not cause installation to fail. Running npm install --no-optional will prevent these dependencies from being installed.

dependencyのインストールに失敗する可能性があり、失敗があった時にもエラーが起きないことを示す時に使います。
例えば、環境によってインストールに失敗することが想定されており、プログラム内でそのエラーをキャッチして処理を継続させられる時などに使うようです。

peerDependenciesMeta

以下のように使い、peerDependenciesに追加情報を与えます。
"optional": trueとすることで、そのpeerDependenciesがoptionalであることを表現できます。

peerDependenciesは、npm v7以降自動でインストールされますが、この設定をすることで自動でインストールする必要がないことを示せます。

{
  "name": "tea-latte",
  "version": "1.3.5",
  "peerDependencies": {
    "tea": "2.x",
    "soy-milk": "1.2"
  },
  "peerDependenciesMeta": {
    "soy-milk": {
      "optional": true
    }
  }
}

これの使い道としては、peerDependenciesとしてサポートするバージョンを指定したいものの、それをインストール必須にしたくない時などです。

webpack-cliにおいて、@webpack-cli/serveでwebpack-dev-serverがoptionalとして設定されていますが、これはserveコマンドを実行するときにはwebpack-dev-serverが必要なためのようです。

参考

7
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1