Copyright © 2024 Roshan Gautam. All rights reserved.
Make changes to node_module files with patch-package
If you have been working with Javascript, I am sure you have been in a situation where you found a perfect npm library for a feature but you have to make some changes there because of any compatibility issues or bugs.
What will you do ?
I know what. One of these, right ?
- Fork the repository, make changes, send PR and wait for the PR to be merged
- Fork the repository, make changes, install from git or even publish your own npm module and use it.
This would normally be okay for smaller projects/libraries where PRs gets merged quickly or you don't care about publishing yet another unmaintained library.
You can use a npm package called patch-package that actually allows you to make changes to node_modules files directly, and yeah you don't have to worry about the changes being deleted with a fresh yarn installation. Sounds cool, huh?
Recently, I came across the exact problem. I had to make a minor change within the react-native folder inside node_modules to fix an issue. The issue was fixed in the new version of react-native but I dare not upgrade my react-native project because you know it's still a pain in ass to upgrade a react-native project. This is how I used patch-package to fix the issue and stay happy.
Let's talk about the issue before moving forward. The problem is with the image not showing up in the iOS app when building with XCode 12. (This is for the people who are here to solve this particular problem.)
First and foremost, you install the package.
yarn add patch-package
Now it's time to make changes to our react native code or, in other words patch the reactive native code
-
Open the file
node_modules/react-native/Libraries/Image/RCTUIImageViewAnimated.m
-
Edit the source code as follow:
From:
#pragma mark - CALayerDelegate - (void)displayLayer:(CALayer *)layer { if (_currentFrame) { layer.contentsScale = self.animatedImageScale; layer.contents = (__bridge id)_currentFrame.CGImage; } }
To:
#pragma mark - CALayerDelegate - (void)displayLayer:(CALayer *)layer { if (_currentFrame) { layer.contentsScale = self.animatedImageScale; layer.contents = (__bridge id)_currentFrame.CGImage; } else { [super displayLayer:layer]; } }
-
Now Make Patch
npx patch-package react-native --use-yarn
-
Track the patch files in git
git add patches/*
-
Add package script for applying patches
"scripts": { ... "postinstall": "patch-package", }
DONE! YES DONE!
From now onwards, whenever you install new packages, it will patch from all your patch files. Voila!
Note: I usedreact-native
library as an example here but you can apply this technique to any other libraries.
Thanks for reading! See you in my next blog.