Skip to content

Add external dependency

matthew harwood edited this page Apr 20, 2016 · 35 revisions

Quick example: in this example we'll show how you can add angular2-jwt to the angular2-seed.

  1. Install the npm dependency.
npm install angular2-jwt --save
  1. Reference the dependency inside of any TypeScript file part of the project.

Inside src/client/app/+about/components/about.component.ts use:

import * as jwt from 'angular2-jwt/angular2-jwt';
// ...
console.log(jwt.AuthConfig);
  1. Potentially restart the server: control+c > npm start, as hot module reloading may fail.
Could not find input file /Users/mharwood/projects/labs/angular-seed/angular2-seed/src/client/src/client/hot_loader_main.ts. This is probably an issue of gulp-typescript.
Please report it at https://github.com/ivogabe/gulp-typescript/issues

For such library you don't need NPM_DEPENDENCIES, since in dev it is loaded with SystemJS, and in production browserify will bundle it based in the reference in about.component.ts.

If you are going to import modules via SystemJS, which is typically the case, you must edit its configuration for the desired module and eventually all its dependencies.

The typical steps are (using angular2-jwt as a sample):

(1) install the package via NPM:

npm install --save angular2-jwt

(2) in tools/utils/project.config.ts, add to the end of the constructor code:

(<any>this.SYSTEM_CONFIG_DEV.paths)['angular2-jwt'] =
        `${this.APP_BASE}node_modules/angular2-jwt/angular2-jwt`;

(please notice the cast to any to avoid TS compile errors). This effectively adds a property named angular2-jwt to the options object used to configure SystemJS, whose value is a path to the target module. Note that the APP_BASE variable can be used to represent the base path of the seed (the one immediately above node_modules).

(3) in main.ts, add the required dependency injection support. For angular2-jwt we typically need to inject AuthHttp (remember to import HTTP_PROVIDERS too!):

    import {Http, HTTP_PROVIDERS} from 'angular2/http';
    import {AuthHttp, AuthConfig} from 'angular2-jwt';
    //...
    bootstrap(AppComponent, [
      ROUTER_PROVIDERS,
      HTTP_PROVIDERS,
      provide(APP_BASE_HREF, { useValue: '<%= APP_BASE %>' }),
      provide(AuthHttp, {
          useFactory: (http: Http) => {
            return new AuthHttp(new AuthConfig(), http);
          },
          deps: [Http]
      }),
    ]);

(4) usage example:

import {AuthHttp} from 'angular2-jwt/angular2-jwt';
//... use in your code ...