npm install --legacy-peer-deps 究竟做了什么?什么时候推荐/什么是潜在的用例?

2022-01-31 00:00:00 reactjs node.js javascript npm npm-install

Just ran into this error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: nexttwin@0.1.0
npm ERR! Found: react@17.0.1
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 react-hook-mousetrap@2.0.4
npm ERR! node_modules/react-hook-mousetrap
npm ERR!   react-hook-mousetrap@"*" from the root project
npm ERR! 

The module I am trying to install seems to have a different peer dependency from what I have installed. It seems like npm changed its behaviour in this regard and now lets the install fail.

What can I do now to fix this? I don't want to downgrade my React version for this.

I know there is a flag called --legacy-peer-deps but I am not sure what exactly this does and whether it's recommended to use it / what the potential disadvantages are? I assume there is a reason npm did let the install fail.

It's just strange because I was using yarn up until very recently and everything was fine.

解决方案

Here's how I solved this problem:

First, what's happening: react-hook-mousetrap is looking for react@16.8.0, but it is not finding it. Instead it is finding @react17.0.1, which is a newer version. For some reason mousetrap doesn't like this newer version, and you are being notified (it is not a big deal, but they decided it was worth stopping your build).

One solution: forcibly install the specific version of react that mousetrap wants:

yarn add react@16.8.0

What this does is roll back your react version to a slightly older one that is compatible with mousetrap. You won't notice any difference, and in future iterations, hopefully mousetrap is updated, so this goes away.

Another solution: make a sweeping decision to not install any older version dependencies:

npm add xxxx --legacy-peer-deps

What this does is ignore old dependencies for this package. It is more comprehensive, and makes a lot of the decisions for you.

相关文章