Http Hobo

Another blog with web-development tips’n’tricks. | About me

Using non-npm 3rd-party library with Ionic application

I’m currently working on an Ionic application, which involves Google Maps. I tried native plugin, but had not much luck with it, furthermore it doesn’t work with GeoJson, which I need. Thus I decided to go with Google Maps JS API for now and had to find out the way to use 3rd-party library within Ionic app.

According to Ionic documentation it should be smooth and easy. But this works only for npm libraries. What if you need to use a library which is injected into a project in an old-fashioned way using <script src="..."></script> tag?

The main complication is that when we use pure JS, we add a script to the page and then use the following code to create a map:

var map = new google.maps.Map(document.getElementById('map'), {
  // some options here

It wouldn’t work with TypeScript, because TS would be unaware of “google” class, therefore will throw an error during compilation.

That’s what “typings” are needed for. Typings is a set of libraries containing definition of types needed for external libraries, so they can be used with TypeScript.

When I googled the matter, I’ve found the following solution:

npm install typings --global
typings install dt~google.maps --global --save

Don’t use it, correct way today is to use npm module @types/*. In my case it would be:

npm install @types/googlemaps

This is actually described in a documentation for which I’ve provided a link above.

But that’s not a big deal. Big deal is about how to let your project know about these typings. Remember – our library is not a NPM module. By default it will say Cannot find namespace “google”. I’ve googled and tried the following import statements:

// TS2306: '.../@types/googlemaps/index.d.ts' is not a module.
import {google} from "@types/googlemaps";
// Cannot find module @types/googlemaps
import "@types/googlemaps";
// TS2306: '.../@types/googlemaps/index.d.ts' is not a module.
import * as googlemaps from "@types/googlemaps";

It all didn’t work.

After couple hours of fighting with this, solution was found:

  1. Remove any import statement.
  2. Go to tsconfig.json file in your app and add the following records into “compilerOptions” section:
compilerOptions: {
  "typeRoots": ["./node_modules/@types"],
  "types": ["googlemaps"]

You are welcome!

P.S. While writing this article another solution was found on Stack Overflow:

import {} from '@types/googlemaps';

And there is no need to deal with tsconfig.json file.