patch-package saves our life - TIL
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.
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:
- Install
patch-package:
npm install patch-package --save-dev- Make changes to a file inside
node_modules. In this case, I modified thestdnumlibrary to handle Thai national ID numbers with the prefix0x:
- Run
patch-packageto create a patch file:
npx patch-package stdnumAfter run, a patch file will be created inside the patches directory in your project.
- Add a
postinstallscript in yourpackage.jsonto apply patches automatically after every install:
"scripts": {
"postinstall": "patch-package"
}Test the result again, it's working perfectly.
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.