patch-package saves our life - TIL

sonht1109,nodejsjavascript

Have you ever needed to make quick fixes to your project's dependencies but then realized you couldn't modify them directly? This is where patch-package comes to the rescue.

Long time no see. I'm too busy to adopt AI now, so no time for new posts hahaha. By the way, I have just known about patch-package recently from my leader. It's so kinda cool so that I need to share it here right away.

Situation

In our case, we are using stdnum to validate Thai national ID numbers. But until we deployed, we just realized that, a lot of our users had IDs with prefix 0x, which is being treated as invalid (opens in a new tab) by the library.

patch-package saves our life

Too urgent to wait for the library to fix it, we needed a quick solution.

What is patch-package?

patch-package is a tool that allows you to make and keep changes to your project's dependencies. Normally, you cannot directly modify the code inside node_modules because it will be overwritten whenever you reinstall your dependencies. patch-package solves this problem by creating patch files that are applied after every install.

Here's a basic usage:

  1. Install patch-package:
npm install patch-package --save-dev
  1. Make changes to a file inside node_modules. In this case, I modified the stdnum library to handle Thai national ID numbers with the prefix 0x:
patch-package saves our life
  1. Run patch-package to create a patch file:
npx patch-package stdnum

After run, a patch file will be created inside the patches directory in your project.

patch-package saves our life
  1. Add a postinstall script in your package.json to apply patches automatically after every install:
"scripts": {
  "postinstall": "patch-package"
}

Test the result again, it's working perfectly.

patch-package saves our life

Easy, right? Just a few steps and you can both use your dependencies and add your own fixes.

Notes

Just one small thing I'd recommend: it's better to lock the versions of your dependencies in package.json so that your patches remain compatible with the installed versions.

References


Thank you for reading. Welcome all your comments/feedbacks.


© 2023 - 2026 by sonht1109