How to patch a Capacitor plugin¶
Today i will show you how to apply small changes to a Capacitor plugin without forking or maintaining the entire plugin. This is especially helpful if you need a hotfix for a plugin that is not yet available in the official version, but can also be useful in many other scenarios.
For this, we will use the npm package patch-package by David Sheldrick.
patch-package
lets app authors instantly make and keep fixes to npm dependencies. It's a vital band-aid for those of us living on the bleeding edge.
This means that we can make changes to the source code of a plugin and then create a patch that will be applied automatically when the plugin is installed.
Preparation¶
Before you can create your first patch, you need to install the npm package:
You should also add the following script to your package.json
:
This will automatically apply all patches after each installation of the npm dependencies.
Create a patch¶
Now let's create your first patch:
- Identify the issue: First, you need to identify the issue you want to fix. For example, there could be a compatibility issue with a specific version of a dependency.
- Make the necessary changes: Now you can make the necessary changes to the source code of the plugin.
In this case, we will change the version of the dependency
FirebaseCrashlytics
from10.8.0
to>= 10.8.0
: - Create the patch: After you have made the necessary changes, you can create the patch by running the following command:
Note: You have to replace
<package-name>
with the npm package name of the plugin you want to patch (e. g.@capacitor-firebase/crashlytics
). This will create a new folder calledpatches
in the root directory of your project and a patch file inside it. The patch file should look something like this:
That's it! Now you can commit the patch file and share it with your team.
Conclusion¶
patch-package
is a great tool to quickly apply small changes to your npm dependencies and is therefore especially useful in Capacitor projects.
However, you should be aware that it is not suitable for larger modifications, as you have to review the patches after each update of the npm dependency and adapt them if necessary.
Besides that, you should always report issues to the plugin author and create a pull request if possible.
This way, the plugin author can review your changes and integrate them into the official version of the plugin.