NPM Package modification with patch-package
💾

NPM Package modification with patch-package

Tags
Published
Author
When working with open-source projects and npm packages, sometimes there are minor tweaks or bug fixes you want to make without going through the entire pull request process. That's where patch-package comes in, a handy tool I learned about today.
Patch-package lets you modify an npm package in your node_modules directory, then creates a .patch file that you can commit to your project's source control. Essentially, you can keep a record of the modifications and apply them whenever you reinstall or update your node modules. This tool is a great way to manage necessary changes without directly altering the original package code.
You can simply make changes in the package code in your node_modules, and then run npx patch-package <package_name> to create a patch file. Later, you can apply this patch using npx patch-package during the installation process in your postinstall script. This ensures that your changes persist across different environments or after a fresh install.
  1. Navigate to the package code in your node_modules folder and make your changes. For instance:
// node_modules/some-package/index.js exports.someFunction = function() { // Original implementation // ... // Modified implementation console.log('Function has been patched'); // ... }
  1. After making your modifications, you need to create a patch. From the root directory of your project, you can run the following command:
npx patch-package some-package
This will create a file in a directory called patches with a name like some-package+0.0.1.patch.
  1. Then, you'll need to make sure this patch gets applied every time your project is installed. In your package.json, you'll add a postinstall script:
{ "scripts": { "postinstall": "patch-package" } }
Now, every time you or someone else installs your project with npm install, your modifications to some-package will be applied!