user68311 user68311 - 5 months ago 44
TypeScript Question

Differences between import options for 3rd party libraries in typescript/Angular 2

What's the difference between:

import * as jslibname from 'jslibname'

declare var jslibname: any;

For example, for firebase, I need
declare var firebase: any;

For moment, I need
import * as moment from 'moment';

What's the logic here? When do I use one or the other?

This is with the Angular CLI and systemjs by the way.


When you do

import * as library from 'library';

you are really importing the library and you can start using it. If you try to use it without importing before you would gen en error. Sometimes the library is being imported already in some place in your app but you just have to use it. You can and the app will work but I guess that in your case the TS compiler throws an error (and probably your IDE marks it as an error). This is because there is no typing definition file for your library (.d.ts). The easiest way to fix it is to do

declare var library: any;

This is telling the TS compiler that library exists and stops throwing an compilation error (also IDE stops complaining).