记录学习修改node_modules中依赖的源码(避坑)

背景:

开发时,当第三方库没有实现想要需求,或者想要样式。

这里一般能想到可以直接修改node_modules的源代码,但是这样不利于协作开发。

本质上,要修改依赖,是为了扩展现有的功能,填补需求,这就类似于打补丁了。

学习研究后,patch-package可以帮助解决这个问题。

例子:

以element-plus为例:修改badge组件最大值的 " + "号*

安装vue3 + element-plus基本步骤就省略了。

  1. 安装 npm i patch-package

  2. 在 package.json ; script中加上这个脚本命令
    附:“scripts”属性中的脚本

      "scripts": {
        "postinstall": "patch-package"
      },
    
  3. 在node_modules修改源码

    **重要:**首先确认我这个vue + vite 工程 是 “type”: “module”;ESM , 所以修改的是\node_modules\element-plus\es\components\badge才对,修改lib不生效,lib使用的是CommonJS .

  4. npx patch-package

    执行命令生成 patch-package补丁文件: npx patch-package element-plus

  5. 加入到版本管理就可以协作开发了。

以下就是生成的补丁文件:

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、stop
  • preshrinkwrap, shrinkwrap, postshrinkwrap: 伴随 npm shrinkwrap 命令(用于固定依赖包版本)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值