exhtml
6/27/2018 - 6:14 AM

(raw) Angular 2 including external javascript libraries


// src/typings.d.ts
declare module 'hc-sticky';

// quotes-results.component.ts
import * as hcSticky from 'hc-sticky';

...

ngAfterViewInit() {
  // DOM is available

  const Sticky = new hcSticky('aside', {
    stickTo: 'main',
    queries: {
      980: {
        disable: true
      }
    }
  });
}

Example: adding underscore.js

install library:
npm install --save underscore

Import the library into Angular (TypeScript)

TypeScript needs to understand underscore.js: when we are going to use an external library such as underscore we need to declare type definitions for TypeScript. TypeScript provides declaration files (*.d.ts) which define types and standardize a JavaScript file/libraries for TypeScript. Some libraries includes typing file, but in case a library does not have .d.ts file, you need to install it. Use TypeSearch: https://microsoft.github.io/TypeSearch/ to find declaration file for the libraries you need. Here you'll find underscore.js declarations file:
npm install --save @types/underscore

Import type declaration into Angular app

app.component.ts
import * as _ from 'underscore'; or simply:
import 'underscore';

TypeScript in that component now understand _ and it easily works as expected.

How to use a library which does not have type definition?

Create/edit src/typings.d.ts and add your package to it:
declare module 'your-library'
In your TypeScript now you need to import it by the given name:

import * as yourPreferedName from 'your-library';
yourPreferedName.method();

////

declare module '*';
The wildcard allows third party JavaScript libraries to be used even if they don’t include type definitions. This means the following would be acceptable in the project:

import * as base64 from "base-64";
import * as utf8 from "utf8";