dev Await
March 2025
How to Use patch-package to Modify npm Packages
Sometimes, you might need to tweak an npm package to fix a bug or adjust its behavior. However, directly modifying node_modules isn’t a good idea because updates can overwrite your changes. This is where patch-package comes in handy. It allows you to patch npm packages safely and ensure the changes persist across installs.
Why Use patch-package?
Fix bugs in third-party dependencies without waiting for updates.
Customize library behavior without forking the entire package.
Retain changes across
npm installoryarn install.
Getting Started
To use patch-package, follow these simple steps:
Step 1: Install patch-package
Run the following command in your project:
npm install patch-package --save-devOr, if you’re using Yarn:
yarn add patch-package --devStep 2: Modify the Package Code
Locate the package inside
node_modules.Edit the necessary file to apply your changes.
Step 3: Create a Patch
After modifying the package, run:
npx patch-package package-nameFor example, if you modified axios, use:
npx patch-package axiosThis will create a patch file inside the patches/ folder.
Step 4: Apply Patches Automatically
To ensure patches are applied after every install, add this script to your package.json:
"scripts": {
"postinstall": "patch-package"
}Now, every time you run npm install or yarn install, the patch will be applied automatically.
Example: Fixing a Bug in an npm Package
Let’s say you found a bug in axios. Here’s how you can fix it:
Open
node_modules/axios/lib/adapters/http.js.Make your changes (e.g., fixing a timeout issue).
Save the file.
Run:
npx patch-package axiosCommit the generated patch file inside
patches/.
Now, even if axios is updated, your fix will persist until the package itself resolves the issue.
Conclusion
patch-package is a powerful tool that allows you to make temporary fixes and customizations without modifying node_modules manually. This ensures your changes remain intact across dependencies updates. Use it wisely to maintain your project’s stability without waiting for official package updates!
For more useful development tips, stay tuned to DevAwait! 🚀
