npm包打补丁 — patch-package

2,501 阅读1分钟

1.背景

在开发过程中(尤其是基于第三方平台)遇到 npm 包与当前环境有兼容性问题时,需要改动 npm 包内文件。一种方法是将需要改动的文件复制出来一份放在项目中引用或者每次手动替换;但这也太不 intelligent 了,所以我采用了 patch-package 添加补丁的方式。 (npm >=5 或者 yarn) 官网

2.使用(以 yarn 为例)

1. 安装,yarn add patch-package -D/-g
// 官方推荐同时安装 postinstall-postinstall
yarn add patch-package postinstall-postinstall

为什么使用postinstall-postinstall(官方说明)

简单来说就是在使用 yarn/yarn add 等命令时补丁一定会生效,使用 yarn remove 时不一定生效,postinstall-postinstall 就是用来解决这个问题的。 下面举个例子,现在有 packageA 的 npm包,此时修改了 packageA。

  • a. 没有 postinstall-postinstall 时,运行 yarn/yarn add 会自动运行补丁;运行 yarn remove exceptPackageA 补丁不生效。
  • b. 有 postinstall-postinstall 时,运行 yarn/yarn add/yarn remove exceptPackageA 都会自动打补丁。
2. 在 package.json 中添加命令
 "scripts": {
+  "postinstall": "patch-package"
 }
3. 修改 npm 包,并运行补丁命令
yarn patch-package package-name
// 例如:yarn patch-package packageA

此时在项目跟目录下会生成patches/packageA+x.x.x.patch 文件,并在文件中记录修改内容。 如下图,在 /node_modules/swiper/cjs/react/get-params.js 文件中将 require("../../core") 改成 require("swiper")。

企业微信截图_1635159459273.png

4. 验证补丁是否生效,移除 npm 包并重新 yarn,如果修改的内容还在则补丁生效
5. 将补丁上传到 git