整理一下,使用 npm
的前端工程如何修改 node_modules
中的源码而不影响部署。
借助两个 package
: patch-package
和 postinstall-postinstall
(用于兼容yarn
)。
安装
$ yarn add patch-package postinstall-postinstall -D
复制代码
修改源码
找到你要进行修改的的第三方库源码进行操作
生成修改记录
$ npx patch-package ${package_name}
复制代码
${package_name}
修改成你刚刚修改的第三方包名,如:element-ui
。此时会在项目根目录生成 patches
目录,里面存放了本次对第三方包的修改(其实就是git diff)
添加脚本
在 package.json
的 scripts
中新增一条记录:
{
"scripts: {
"postinstall": "patch-package",
...
}
}
复制代码
postinstall
原本是 npm
命令的一个 hook
,借助 postinstall-postinstall
,他会在 npm install
或者 yarn
(甚至 yarn remove
) 之后执行,所以会完成我们在 patches
目录中对第三方包的调整。
提交修改
感谢阅读!!!