Patch That Package

You probably know this situation. You are working on a project and one of the npm packages you are working with contains a nasty bug or is lacking a critical feature. Of course, you first head over to the repository, e.g. on GitHub, and draft an issue. Maybe you even write a fix yourself and create a pull request. But, depending on the project, it might take a while until someone finds the time to review your issue or merge and publish the pull request. Sometimes, the project even is completely unmaintained. Whatever the reason, you might want to patch the package yourself to be able to move on. So what do you do?

Wouldn’t it be ideal to be able to fix the issue immediately but still maintain the connection to npm, being able to update the package with all other dependencies?

This is what patch-package does.

You install it via npm

npm i -D patch-package

And add a script command to your package.json file that runs after npm install:

"scripts": {
+  "postinstall": "patch-package"

Now you can fix the bug in one of your dependencies, hit save, and, when you’re done, run:

npx patch-package your-package-name

This will create a .patch file that contains your changes. All the patches you create this way are then applied automatically when you use npm (or yarn).

Patch-package might not be the right solution for larger fixes or when you are writing a change that is really consequential. Also keep in mind that you might not be able to oversee all the consequences of a change, also regarding other packages. But for minor fixes, patch-package can save your day.

And, once your pull request has been merged, you can – and should – remove your patch again, of course.


2 Webmentions