当 npm 包出现问题时,最简单的修补方法是🐛
当你在开发基于 npm 的项目时,如果遇到某个依赖项出现问题,你会怎么做?
-
最简单的方法(实际上大多数开发者都是这么做的)是去 GitHub 的软件包仓库提交 bug 报告。但这样做真正的问题在于维护者可能没有足够的时间来修复它。不幸的是,截止日期临近,你至少需要在接下来的几周内找到其他方法。
-
先 fork 出问题的包,修复它,然后提交一个 PR。乍一看这似乎是个不错的解决方案,但这也意味着你需要将修改保存在本地,直到维护者批准更改并将其合并到主分支。
嗯,接下来怎么办?
- 在这种情况下,最好的方法是对依赖项进行更改,然后使用 npm 的 'patch-package' 命令应用修复。但是等等……这具体该如何操作呢?其实很简单:
1) 修复依赖项中的一个错误:
nano node_modules/react-redux/dist/react-redux.js
console.log('Hi I am a redux patch');
2)安装补丁包:
npm install patch-package -D
或者通过 Yarn:
yarn add patch-package postinstall-postinstall --dev
此外,还要添加安装后脚本:
"scripts": {
"postinstall": "patch-package"
}
3) 运行 patch-package 命令创建 .patch 文件
npx patch-package react-redux or yarn patch-package react-redux
这将产生以下变化:
diff --git a/node_modules/react-redux/dist/react-redux.js b/node_modules/react-redux/dist/react-redux.js
index c56d7f2..3a2b1e2 100644
--- a/node_modules/react-redux/dist/react-redux.js
+++ b/node_modules/react-redux/dist/react-redux.js
@@ -27,6 +27,8 @@
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
+ console.log('Hi I am a redux patch');
+
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
4) 通过 npm 包管理器应用您的修复程序:
npm install or yarn install
5)添加分阶段的更改:
git add .
git commit -m 'bugfix/react-redux: Fix a react-redux bug'
git push origin bugfux/react-redux
谢谢,希望您喜欢这篇文章!祝您
编程愉快!😊