patch-package,顾名思义是给npm包打补丁,可以修改npm包的源码,每次项目构建都会生效,有效的实现一些奇怪的需求,下面以react-native-echarts-pro/1.8.9为例
一、安装
npm i patch-package --save-dev
二、去node_modules里修改源码,文件路径:node_modules/react-native-echarts-pro/src/components/Echarts/index.js
在useImperativeHandle里新增了调用方法clear,源码里本来是没有的
...
useImperativeHandle(ref, () => ({
clear () {
eChartRef.current?.postMessage(
JSON.stringify({ type: "clear" })
);
},
...
});
三、生成补丁,在根目录下执行 npx patch-package react-native-echarts-pro
在根目录下会生成补丁文件 /patches/react-native-echarts-pro+1.8.9.patch +1.8.9是npm包的版本
Watchout:每次patch都对应一个源码版本,如果你升级了版本,对应的patch就会失效,需要重新手工打补丁
// 部分代码
...
diff --git a/node_modules/react-native-echarts-pro/src/components/Echarts/index.js b/node_modules/react-native-echarts-pro/src/components/Echarts/index.js
index 3014574..ba11092 100644
--- a/node_modules/react-native-echarts-pro/src/components/Echarts/index.js
+++ b/node_modules/react-native-echarts-pro/src/components/Echarts/index.js
...
@@ -28,7 +29,12 @@ function Echarts(props, ref) {
* Parent can use ref to call the methods.
*/
useImperativeHandle(ref, () => ({
- setNewOption(option, optionSetting) {
+ clear () {
+ eChartRef.current?.postMessage(
+ JSON.stringify({ type: "clear" })
+ );
+ },
+ setNewOption (option, optionSetting) {
...
四、修改package.json,加上这段指令,这样每次install的时候就会自动打补丁
...
"scripts": {
"postinstall": "patch-package",
...
yarn
...
[4/4] 🔨 Building fresh packages...
success Saved lockfile.
$ patch-package
patch-package 6.2.2
Applying patches...
react-native-echarts-pro@1.8.9 ✔
✨ Done in 66.14s.
五、最后别忘记推送到远端,告诉别人pull下来重新install