Importing JS libraries in Angular 2+ the right way

Yonathan Meguira
1 min readJan 25, 2018

ever felt like you don’t care, like type any? I do.

When building a TypeScript app, there are times when you feel like a gangster and you decide to use a JS library without it’s @types. Thug Life !

So how should you go about that ?

So we know two things for sure:

A) At some point we’ll need to ‘import’ the library

B) At some point we’ll need to use it

Importing the Library

I know we decided to be real thugs, but please do not import the JS files into index.html, please don’t do that.

Instead import them relative to their paths inside .angular.cli.json in the scripts array.

Using the library

Then you need to make this library globally available: for this purpose, go to your component and write the following : declare var mylibrary: any;

Then you should be good to go and use as you please anywhere in that component :

const myLib = mylibrary.someMethod();

Bonus

If you wish to make that available in multiple components at once, then simply declare your library var in your ‘app.component.ts’;

That’s it for this ‘code like you don’t care’ tutorial

--

--