npm install:Could not resolve dependency:peer... 原因和解决方案

3,046 阅读2分钟

新down公司一个之前的项目,在公司的电脑上npm install是没问题的,到家里的电脑npm install 就报错; 报错日志如下:

npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: shopping-mall@1.0.0 npm ERR! Found: echarts@5.2.2 npm ERR! node_modules/echarts npm ERR! echarts@"^5.2.1" from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer echarts@"^4.1.0" from vue-echarts@4.1.0 npm ERR! node_modules/vue-echarts npm ERR! vue-echarts@"^4.0.1" 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.

家里的node 和npm 跟公司不一样 上述报错日志中有个关键字眼:this command with --force, or --legacy-peer-deps

于是我查了一下是什么意思: 搜索得出这样的答案:

修复上游依赖性冲突,或使用--force或--legacy-peer-deps重试此命令,以接受不正确的(并且可能会损坏的)依赖性解析。

-f或–force参数将强制npm获取远程资源,即使磁盘上存在本地副本也是如此。
同时,用于的文档--legacy-peer-deps说:
–legacy-peer-deps:安装时忽略所有peerDependencies,其样式为npm版本4到版本6。
在新版本的npm(v7)中,默认情况下,npm install当遇到冲突的peerDependencies时将失败。以前不是那样的。

两者之间的区别如下-

--legacy-peer-deps:安装时忽略所有peerDependencies,采用npm版本4到版本6的样式。 --strict-peer-deps:遇到任何冲突的peerDependencies时,失败并中止安装过程。默认情况下,npm仅会因根项目的直接依赖关系而导致的peerDependencies冲突而崩溃。

以上是英文文献翻译过来的,是有点生硬:我简单总结一下: 在新版本的npm(v7)中,默认情况下,npm install当遇到冲突的peerDependencies时将失败。不会继续安装,并提示:

Fix the upstream dependency conflict, or retry
this command with --force, or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.

这样的关键字,这是npm版本的依赖冲突的提示使然,
那么npm:何时使用--force和--legacy-peer-deps?
--force 会无视冲突,并强制获取远端npm库资源,即使本地有资源也会覆盖掉
--legacy-peer-deps:安装时忽略所有peerDependencies,忽视依赖冲突,采用npm版本4到版本6的样式去安装依赖,已有的依赖不会覆盖。
建议用--legacy-peer-deps 比较保险一点,反正我用了就安装成功了;