Site icon Mobile App Development Services

How to Patch NPM Packages

Sometimes when we have several packages installed in our applications and we see that one of the packages has a broken functionality out of nowhere. At that point time, we are left with the following options:

With our understanding ready about the patch-package, lets see how to use it:

Make sure you’re at the root of your project, and from there run the following command from terminal:

yarn add redux

Or

npm i redux

Next we install and setup, “patch-package”, again from your terminal run:

npm i patch-package

or

yarn add patch-package postinstall-postinstall

Why did we install postinstall-postinstall? Details are at the bottom.

Next we add a script in package.json which will be execute after the yarn or npm installation is completed:

“scripts” : {
    “postinstall”: “patch-package”
}

Now we are all set to make some changes to redux package and let’s assume it isn’t working and we’re going to fix it by:

Now we will run the following command from the terminal:

yarn patch-package redux

Or 

npx patch-package redux

This will now create a patches directory at your root folder. Inside of it, you will see a redux+4.1.2.patch file. The numbers in the file name represent the currently installed redux version from package.json.

That’s it. We are now free from all the worries. Now when you commit this patch file, it will be stored alongside your other files on your project’s GitHub repository.

There’s one last thing and that is to test our implementation. Let’s remove the redux package by running:

yarn remove redux

Or

npm uninstall redux

Now we don’t have our console.log as a fix in the redux package as we completely removed redux. Let’s re-install redux and see if the patch-package applies our changes which are created as a patch in the patches folder.

Run following in the terminal:

yarn add redux

Or

npm i redux

Now if we go to node_modules/redux/src/index.js, we see our console.log living there. Congrats, you’ve bandaged the redux package successfully.

Why did we install “postinstall-postinstall” package when installing through yarn? 

The answer is when we run yarn, yarn add, yarn remove, Yarn actually replaces your current node_modules with a fresh installation.  And in the case of running yarn remove, Yarn doesn’t call the post install hook. So the “postinstall-postinstall” package actually calls the post install hook after every yarn remove call. So if we didn’t install this postinstall-postinstall package, what would’ve happened is that our patch wouldn’t have been executed and our application won’t work then.

Thanks for reading, Don’t forget to share your thoughts in comment section!

For reference:

https://www.npmjs.com/package/patch-package