Skip to content

Add external dependency

ComFreek edited this page Nov 3, 2017 · 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. In tools/config/project.config.ts add the following code in the constructor:
  // Add packages (e.g. angular2-jwt)
  let additionalPackages: ExtendPackages[] = [{
    name: 'angular2-jwt',
    // Path to the package's bundle
    path: 'node_modules/angular2-jwt',
    packageMeta: {
      defaultExtension: 'js',
      // main: 'dist/lib/index', possibly required for your package, see description below
    }

  }];

  this.addPackagesBundles(additionalPackages);

Let's say you have a package your-package which has a your-package/index.d.ts importing and re-exporting some types, which are actually defined in your-package/dist/lib/index.js. Then import abc from 'your-package' must be resolved to import abc from 'your-package/dist/lib/index.js'. In such a case, using the main key is required. Otherwise, you get strange syntax errors when using gulp serve.dev (and only in dev mode!) in the JS console because node_modules/your-package is fetched resulting in the server returning index.html, which obviously doesn't parse as JS.

  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);

Testing:

To support the new library for testing the Karma dependencies will need to be updated in karma.conf.js:

// list of files / patterns to load in the browser
    files: [
      'node_modules/zone.js/dist/zone.js',
      'node_modules/zone.js/dist/long-stack-trace-zone.js',
      //...

      { pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: false, watched: false }, // PhantomJS2 (and possibly others) might require it
      { pattern: 'node_modules/angular2-jwt/**/*.js', included: false, watched: false },

In addition, an alias for the import path must be set in test-config.js:

System.config({
  baseURL: '/base/',
  defaultJSExtensions: true,
  paths: {
    'angular2/*': 'node_modules/angular2/*.js',
    'rxjs/*': 'node_modules/rxjs/*.js',
    'angular2-jwt/*': 'node_modules/angular2-jwt/*.js'
  }
});