了解peerDependencies
·
2 min read
package.json中除了dependency和devDependency之外,还有一个peerDependency。这里通过解决一个实际报错来了解下它。
报错信息
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: a@0.0.1-beta
npm ERR! Found: ssh2@1.15.0
npm ERR! node_modules/ssh2
npm ERR! ssh2@"1.15.0" from the root project
npm ERR! ssh2@"^1.12.0" from ssh2-sftp-client@9.1.0
npm ERR! node_modules/ssh2-sftp-client
npm ERR! ssh2-sftp-client@"^9.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer ssh2@"1.16.0" from a@0.0.1-beta
npm ERR! packages/a
npm ERR! a@0.0.1-beta
npm ERR! node_modules/a
npm ERR! workspace packages/a from the root project
npm ERR!
npm ERR! Conflicting peer dependency: ssh2@1.16.0
npm ERR! node_modules/ssh2
npm ERR! peer ssh2@"1.16.0" from a@0.0.1-beta
npm ERR! packages/a
npm ERR! a@0.0.1-beta
npm ERR! node_modules/a
npm ERR! workspace packages/a 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!
npm ERR! For a full report see:
npm ERR! /Users/alanhe/.npm/_logs/2025-01-02T02_53_13_141Z-eresolve-report.txt
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/alanhe/.npm/_logs/2025-01-02T02_53_13_141Z-debug-0.log
错误分析
项目的直接依赖中,ssh2的版本是1.15.0,而包a的peerDependency中,ssh2的版本是1.16.0。
peerDependency作用是使用a包的项目中在安装ssh2的时候,需要使用1.16.0的版本。因此这里报错了。
解决方案
知道了问题的直接原因也就好解决了。解决办法:升级主项目的ssh2版本即可。
总结
- 回头来看peerDependencies。就是说它可以约定限制使用了该包的项目中,依赖目标包的版本。即通过该配置你可以限制运行该包的项目中如果依赖该包,版本必须满足要求。
- peerDependencies声明包,而主项目dependency没有,目前的npm比如v9是不会直接安装的,除非是有其它包有作为依赖,则还是会安装。