ERESOLVE unable to resolve dependency treeの解決方法


背景

Dockerのnodeコンテナ内で、create-react-appでReactプロジェクトを作成し、
その後にmaterial-uiをインストールしようとしたときに、発生したエラーでした。

※調べてみた感じ、npm installで、インストール元のパッケージのバージョンが最新(latest)で、
インストールするパッケージの最新バージョンが同等(peer)でなかったときに発生するエラーのようでした。

結論

そのライブラリをインストールしたい場合は、npm installのあとに、--save --legacy-peer-depsを追加してあげましょう。
もしくは、インストール元のプロジェクトのダウングレードを検討しましょう。。

経緯

# material-uiをインストールしようとしたら。。
npm install @material-ui/core
# このようなエラーが発生。。
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0" from @material-ui/[email protected]
npm ERR! node_modules/@material-ui/core
npm ERR!   @material-ui/core@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /root/.npm/eresolve-report.txt for a full report.

上のログを確認すると、reactのバージョンが17.0.1であるのに対し、
material-ui/[email protected]がサポートしているreactのバージョンは16.8.0でした。(=最新のReactプロジェクトに対応していない。)
なので、依存関係を解決できずエラーになって、インストールができないことに。。

ここで、npm install のあとに、オプションで、--save --legacy-peer-depsを追加しました。
すると、インストールが無事に完了します。

npm installする際に、インストールするライブラリのバージョンが、インストール先のプロジェクトのバージョンに対応していない場合、
オプションで、--legacy-peer-depsを使うことで、半強制的に?installできるようになるようです。
ただ、インストール後に、そのパッケージが期待通りに正しく動くかを、しっかり確認する必要がありそうです。

npm install --save --legacy-peer-deps @material-ui/core

added 29 packages, removed 2 packages, and audited 1720 packages in 18s

117 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

所感

ライブラリを使うときは、そのライブラリの最新版が、どのバージョンと対応しているのか、
実装する前にしっかり調べておくべきなんだなー、、と改めて感じました。
安直に最新版!はアブナイ。。

参考になった記事:https://github.com/mui-org/material-ui/issues/23306