前言
说到 package.json 的版本固定,你或许会想到 dependencies devDependencies 。
"@ant-design/pro-layout": "^4.5.16",
"@antv/data-set": "^0.10.2",
"antd": "^3.23.6",
"classnames": "^2.2.6",
"dva": "^2.4.1",
"echarts": "^4.7.0",
"echarts-for-react": "^2.0.15-beta.1",
"html2canvas": "^1.0.0-rc.5",
"jquery": "^3.5.0",
"lodash": "^4.17.11",
"moment": "2.24.0",
"omit.js": "^1.0.2",
"path-to-regexp": "^3.1.0",
"qs": "^6.9.0",
"react": "^16.8.6",
"react-copy-to-clipboard": "^5.0.1",
"react-dom": "^16.8.6",
"react-helmet": "^5.2.1",
"react-read-more-read-less": "^1.0.7",
"react-to-print": "^2.6.3",
"redux": "^4.0.1",
"slash2": "^2.0.0",
"umi": "^2.9.6",
"umi-plugin-pro-block": "^1.3.4",
"umi-plugin-react": "^1.10.1",
"umi-request": "^1.2.7",
"webpack-theme-color-replacer": "^1.2.15"
},
注意moment那一行,去掉了 ^ 符号。此时版本就被固定了。
但是,这个只对开发者主动引用的依赖有效,对“依赖的依赖”,“依赖的依赖的依赖”是无效的。
举个例子,antd 用了 rc-calendar ,rc-calendar 用了 moment,假设moment最新版是2.4.1,那么,rc-calendar使用的moment仍然是2.4.1,而不是2.4.0。
从package-lock.json中可以看出。
"rc-calendar": {
"version": "9.15.6",
"resolved": "https://registry.npmjs.org/rc-calendar/-/rc-calendar-9.15.6.tgz",
"integrity": "sha512-TJD4cUXsBAjyCzo7BaGb86nZyJetBUt/Rpu0H1WWhp9AJc+Tl7aj7TCD3TM5Y8Ak/yxsA8WDBMuKw1XdQMsM5g==",
"requires": {
"babel-runtime": "6.x",
"classnames": "2.x",
"moment": "2.x",
"prop-types": "^15.5.8",
"rc-trigger": "^2.2.0",
"rc-util": "^4.1.1",
"react-lifecycles-compat": "^3.0.4"
}
},
怎样解决
链接:https://github.com/yarnpkg/rfcs/blob/master/implemented/0000-selective-versions-resolutions.md
文章很长,不看也可以,我们只需要知道怎么解决这个问题。
package.json里面加一个对象,和 dependencies devDependencies 平级。
"resolutions": {
"**/moment": "2.24.0"
},
这样,整个项目中所有的moment的版本都会指定为2.24.0。
但你可能会需要一些更精细的设置(比如只指定“某个依赖的某个依赖的某个依赖”的版本)。你可以从上面的文章李找到答案。
Q&A
- npm是否支持这个设置?
不确定,因为我平时装依赖用的是yarn。