TL;DR: How to patch a node module package after execute npm install
Why the hell do you need to patch a node module package?
Sometimes you are working in a npm project and a module dependency not works properly. You can submit a issue to its CVS (normally GitHub) but you can’t wait until the authors resolve it or approve your PR.
What can we do then? Well, we can patch the package after its installation.
We use a real example: Liferay Angular portlet build process.
Life Angular portlet
To build a 100% Angular Liferay portlet, we use a Liferay’s support libraries (lnbs-*).
It’s works perfectly if we build for a production environment. But, what’s happen if I want to build for pre-production environment? And for QA? DevOps?
Damn it! You can’t (by this moment).
After review the Liferay Build Support code, we can confirm which the “ — prod” build flag is “hardcoded”.
What can we do now?
Well, the solution is simple. Just replace the hard coded flags with optional configuration passed by arguments.
Well, we only have to give it shape and automate the patching.
Creating the patch
Before coding the changes, we create a backup of the file (or files) to change.
After coding the changes directly under node_modules’ package source and test to works properly.
No just execute the
diffcommand to create the patch and saves it into
patches folder (for example).
diff file-orig node_modules/package/src/file-mod > patches/package.patch
The patch file for our examples is the following:
Patching in post-install
Just only we need to apply the patch after the
npm install is executed.
The easiest way is by defining the predefined
package.json just add a command similar to the following:
"postinstall": "patch -N node_modules/liferay-npm-build-support/lib/scripts/build/index.js patches/liferay-builder-conf.patch || true"
And that’s all.
Now when we run the “npm install” the patch will be applied automatically.
Please, if you liked it, give it a round of applause. And if you want to know more about DevOps, Kubernetes, Docker, etc … follow me :)