Ionic v5 (React) Capacitor: Custom Cordova Plugin Usage

I am trying to figure out how to use a Cordova plugin in a Ionic React application. The documentation walks you through how to install plugin and sync it with Capacitor but not how to use a custom plugin that does not have a ionic-natice wrapper. The plugin in question in a Cordova based project is accessed via the window object. Will this be the case with Ionic w/Capacitor?

1 Like

Yes, Cordova plugins work on Capacitor the same way the work in Cordova, so read the plugin docs and use it as they tell you to.

what plugin? what have you tried?

Even when using Typescript? I’ve run into issues with Typescript since Cordova plugins use standard ES.

Here’s the link to the plugin -> https://github.com/darryncampbell/DataWedge-Cordova-Sample

It’s a proprietary Cordova to use the barcode scanner on Zebra devices, specifically their TC7x models

If you use Typescript then the problem is Typescript, not Capacitor, you’ll have the same problem if using Typescript and Cordova. Typescript is not a requirement for Capacitor. In both cases you need to compile the Typescript code and Capacitor (or Cordova) will use the compiled code.

But I think you should be able to use the plugin like this (<any>window).plugins.intentShim instead of window.plugins.intentShim, as if you use it like the last one, Typescript will complain about “Property ‘plugins’ does not exist on type 'Window”, but with (<any>window) it shouldn’t.

Thanks for the response. That’s the issue I’ve ran into, our application is built with react so using the following

const barcodeIntent = (<any>window).plugins.intentShim;

causes a JSX error => Property 'any' does not exist on type 'JSX.IntrinsicElements'.

My initial thought of implementation would be to create a React context to handle registering the scanner event listener, but using the above error I haven’t figured out how to get it to work.

(window as any).plugins.intentShim;

Cool beans! That gets rid of the JSX error. What about the warning:

Unexpected any. Specify a different type.eslint@typescript-eslint/no-explicit-any

I’m fairly new to TypeScript, what would be considered best practice to handle this warning? Or would it be ok to ignore?

you should be able to turn off the no-explicit-any warning from the compiler/linter. Your compiler/linter is currently expecting that you will only use strongly-typed objects, it’s warning you against using any as a type, which doesn’t have any type-checking.

Everything is compiled down to JavaScript in the end, and all the strict typing is only available at compile time, so turning off that rule so you can use a weakly-typed object with dynamic properties (which is what window is) is fine.

1 Like