Angular 2 Add 3rd party library that does not have typings


Example

Notice, this is only for angular-cli up to 1.0.0-beta.10 version !

Some libraries or plugins may not have typings. Without these, TypeScript can't type check them and therefore causes compilation errors. These libraries can still be used but differently than imported modules.

  1. Include a script reference to the library on your page (index.html)

    <script src="//cdn.somewhe.re/lib.min.js" type="text/javascript"></script>
    <script src="/local/path/to/lib.min.js" type="text/javascript"></script>
    
    • These scripts should add a global (eg. THREE, mapbox, $, etc.) or attach to a global
  2. In the component that requires these, use declare to initialize a variable matching the global name used by the lib. This lets TypeScript know that it has already been initialized. 1

    declare var <globalname>: any;
    

    Some libs attach to window, which would need to be extended in order to be accessible in the app.

    interface WindowIntercom extends Window { Intercom: any; }
    declare var window: WindowIntercom;
    
  3. Use the lib in your components as needed.

    @Component { ... }
    export class AppComponent implements AfterViewInit {
        ...
        ngAfterViewInit() {
            var geometry = new THREE.BoxGeometry( 1, 1, 1 );
            window.Intercom('boot', { ... }
        }
    }
    
    • NOTE: Some libs may interact with the DOM and should be used in the appropriate component lifecycle method.