Type Declarations for Cordova Plugins
I've been doing some Cordova plugin development recently and at some point, I've decided to add TypeScript type declarations to make the plugin easier to consume from Ionic (or other TypeScript based) applications.
My first instinct was to include the type definition file in a separate folder inside the Cordova plugin package as is common with regular NPM packages, e.g. types/index.d.ts
. I then added a reference to it in the plugin's package.json
file:
"types": "./types/index.d.ts"
This was enough to get it working while writing code in Visual Studio Code but the project failed to build because the compiler couldn't find the types. Neither importing them:
import `myCordovaPlugin`;
nor adding them as reference types helped:
/// <reference types="myCordovaPlugin" />
I decided to do some research of existing Cordova plugins to find a working solution. Thanks to Ionic Native there's usually no need to use type definitions for Cordova plugins even when they are available.
Since many plugins distribute type definitions the same way I tried to do it, I did some tests without using Ionic Native and had the same problem as with my plugin. I couldn't get the project to build no matter what I tried. Only plugins that have type definitions in a separate package worked for me, e.g. @types/cordova-plugin-scanner.
I did the same for my plugin and it worked flawlessly without any imports. Of course, I had to make sure that my tsconfig.json
file in use had the typeRoots
compiler option set correctly (without the types
compiler option being present). You can check my previous blog post for more details about that.
I wonder if I'm missing something. I'd expect the type definitions to work even if they are included in the Cordova plugin since that's how they're most often distributed.