Search code examples
reactjscapacitorcapacitor-plugin

How can I "wrap" a capacitor plugin in React so that I can manage it centrally?


Today, Capacitor had a new release that replaced the @capacitor-community/http plugin with a CapacitorHttp plugin.

I'm using Ionic React for my app so all my code is in TypeScript/React.

I want to test out the new CapacitorHttp plugin, but I also want to make it easy to revert back to using the http plugin if things don't work out.

Throughout my app, I have a lot of import statements like import { Http } from '@capacitor-community/http';. In React, is there a way to somehow wrap this import so that I can import MyCustomHttp everywhere, and then in MyCustomHttp, import CapacitorHttp or http? This would simplify my code by putting the import in one place, but I don't know how to do this.


Solution

  • As commented by @Konrad, you can use the { A as B } in a custom file. Here is a code example for the Capacitor Push Notifications plugin:

    PluginPushNotifications.ts

    import {
      ActionPerformed,
      PushNotifications,
      Token,
    } from '@capacitor/push-notifications';
    
    export type { ActionPerformed as PluginActionPerformed };
    
    export type { Token as PluginToken };
    
    export { PushNotifications as PluginPushNotifactions };
    

    To help myself with my IDE's autocomplete, I re-exported everything with a Plugin prefix.