Patching npm Modules

Sometimes it is helpful to patch an npm module. It could be the case that you need to make a simple fix and you don’t want to maintain a fork of the library. The library may have a pull request to fix the issue but you don’t want to use an unmerged branch. For those occasions, the following technique is helpful.

Create Your Patch Folder

First, create a patches folder in the root of your project. I like to call mine node_modules_patches so that it sorts next to the node_modules folder. The structure of the folders in the patches folder should exactly match the structure of the folders of the npm modules that you want to patch. Only the files/folders that need to be patched should be replicated; you don’t need to replicate all of the files/folders

Screen shot of the file structure of the patch folder

In the screenshot above, you can see that I’ve created a patch for the build.gradle file of the react-native-cookies library

Create the Post-Install Script

Next, open your package.json file. We going to create an npm post-install script that will copy the files from the patches directory. If you create a scripts key with a postinstall property, npm will automatically run this after installation is complete. It will end up looking something like this:

{  
  "name": "your_app",  
  "version": "1.0.0", 
  "scripts": {
    "postinstall": "cp -R node_modules_patches/ node_modules/"
  },
  "dependencies": {},
}

As you can see, the post-install script contains a command to copy the files from node_modules_patches to node_modules. The -R option indicates that the entire sub-tree of the patches directory should be recursively copied and should continue even if errors are encountered.

If your project already has a post-install script, you can separate the commands using a semi-colon.

Create Your Patch Files

And that’s basically it! You can now create your patch files. Generally, I’ll start by copying the file from the problematic package. Then I’ll make my edits.

Be sure to run npm install so that any edits you’ve made in your patches folder are copied to the correct place in node_modules. This pattern should also work with yarn

Once the library is fixed at the source, delete any files or folders in your patches folder that are no longer needed. If you keep the node_modules_patches folder, the post-install script will continue to function, even if there are no patches in the folder.

Leave a Comment