Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import multiple 3rd party libraries into same namespace in Angular2 project

I'm making a projet with Angular2. The project is generated with Angular-CLI (1.0.0-beta.17) and uses Angular v2.0.0 with TypeScript.

In this project I would like to import both Leaflet(1.0.1) and Leaflet.VectorGrid(1.0.2).

I install them with npm

npm install leaflet
npm install leaflet.vectorgrid

Leaflet has a @types definition, so i installed that as well

npm install @types/leaflet

Leaflet.VectorGrid however does not have an @types definition, so i add

declare module 'leaflet.vectorgrid';

to my typings.d.ts file instead.

But how can I then import both modules into the same namespace in my project files ?

If I try :

import * as L from 'leaflet';
import * as L from 'leaflet.vectorgrid';

this logically throws a compile error because of the duplicate identifier. Importing them with different aliases, such as :

import * as L from 'leaflet';
import * as LVG from 'leaflet.vectorgrid';

does not work either because Leaflet.VectorGrid extends the global L object so doing

LVG.vectorGrid(...)

fails.

Any help would be appreciated. Thanks.

like image 491
jonasr Avatar asked Dec 07 '25 08:12

jonasr


1 Answers

One solution is to import both librairies into the global scope with script tags. Then adding

declare var L: any;

into any .ts file where L needs to be used will work. However this is not ideal since L is not really typed and no verifications will be made by the typescript compiler.

To be able to use both libraries with types, one would have to write a type definition for the Leaflet.VectorGrid library, which as far as i can tell does not exist right now, and then merge both objects into one.

like image 69
jonasr Avatar answered Dec 08 '25 20:12

jonasr