背景:
开发时,当第三方库没有实现想要需求,或者想要样式。
这里一般能想到可以直接修改node_modules的源代码,但是这样不利于协作开发。
本质上,要修改依赖,是为了扩展现有的功能,填补需求,这就类似于打补丁了。
学习研究后,patch-package可以帮助解决这个问题。
例子:
以element-plus为例:修改badge组件最大值的 " + "号*
安装vue3 + element-plus基本步骤就省略了。
-
安装 npm i patch-package
-
在 package.json ; script中加上这个脚本命令
附:“scripts”属性中的脚本"scripts": { "postinstall": "patch-package" },
-
在node_modules修改源码
**重要:**首先确认我这个vue + vite 工程 是 “type”: “module”;ESM , 所以修改的是\node_modules\element-plus\es\components\badge才对,修改lib不生效,lib使用的是CommonJS .
-
npx patch-package
执行命令生成 patch-package补丁文件: npx patch-package element-plus
-
加入到版本管理就可以协作开发了。
以下就是生成的补丁文件:
diff --git a/node_modules/element-plus/es/components/badge/src/badge2.mjs b/node_modules/element-plus/es/components/badge/src/badge2.mjs
index f4ca28e..e86b811 100644
--- a/node_modules/element-plus/es/components/badge/src/badge2.mjs
+++ b/node_modules/element-plus/es/components/badge/src/badge2.mjs
@@ -21,7 +21,7 @@ const _sfc_main = /* @__PURE__ */ defineComponent({
return "";
if (isNumber(props.value) && isNumber(props.max)) {
if (props.max < props.value) {
- return `${props.max}+`;
+ return `${props.max}...`;
}
return props.value === 0 && !props.showZero ? "" : `${props.value}`;
}
Tips:修改完源码后,重启服务可能还是不生效。看看构建工具的缓存的问题,vite可以看看删除 node_modules下的 .vite 文件。或者删除node_modules,重新安装依赖。
附:
npm 支持运行package.json里“scripts”属性中的脚本,包括:
prepublish
:在npm publish
命令之前运行(也会在不带参数的npm install
命令前运行,详情在下段描述)prepare
: 在两种情况前运行,一是npm publish
命令前,二是不带参数的npm install
命令;它会在prepublish
之后、prepublishOnly
之前执行prepublishOnly
: 在npm publish
命令前执行publish,postpublish
: 在npm publish
命令后执行preinstall
: 在npm install
命令前执行install,postinstall
: 在npm install
命令后执行preuninstall,uninstall
: 在npm uninstall
命令前执行postuninstall
: 在npm uninstall
命令后执行preversion
:在改变包的version前执行version
: 在改变包的version后,但提交之前执行postversion
: 在提交version变更后执行pretest, test, posttest
: 伴随npm test
命令prestop, stop, poststop
: 伴随npm stop
命令restart, start, poststart
: 伴随npm start
命令pre restart, restart, poststart
: 伴随npm restart
命令。提示:假如scripts里没有写restart命令,npm默认会运行start、stoppreshrinkwrap, shrinkwrap, postshrinkwrap
: 伴随npm shrinkwrap
命令(用于固定依赖包版本)