在 package.json
文件里,postinstall
是一个钩子脚本,它在每次运行 npm install
命令后自动执行。当你在该字段中指定 "patch-package"
时,意思是在 npm install
安装所有依赖包之后,自动运行 patch-package
命令。
patch-package
允许用户在不直接修改 node_modules
目录的情况下对安装的 npm 包进行修补(即,应用补丁)。这在您需要对依赖的包进行小修改以修复错误或更改功能时非常有用,但出于某种原因(例如,等待官方修复或是不兼容的版本问题)您不能或不想升级到新版本。
这里是如何在项目中使用 patch-package
的一般步骤:
-
在项目中安装
patch-package
(通常作为开发依赖)和postinstall-postinstall
如果使用 Yarn。npm install patch-package postinstall-postinstall --save-dev # 或者如果你用的是 yarn yarn add patch-package postinstall-postinstall --dev
-
对
node_modules
中的包做出更改。 -
运行
patch-package
来创建一个补丁文件。例如,如果你修改了some-package
:npx patch-package some-package
这个命令会在项目的根目录下创建一个
patches
文件夹,里面包含了修改的补丁。 -
修改
package.json
来添加postinstall
脚本:"scripts": { "postinstall": "patch-package" }
现在,每次运行 npm install
,postinstall
脚本就会执行 patch-package
,应用 patches
目录中的所有补丁到相应的包上。这确保了即使在删除 node_modules
目录并重新安装依赖之后,您的更改也仍然会被应用。