How to import a npm package in an angular2 component?

Lucas Moreira picture Lucas Moreira · Mar 22, 2016 · Viewed 11.4k times · Source

I'm trying to learn the ropes of ng2 and the depedency injection system is killing me.

I'm using the ng quickstart from: https://github.com/angular/quickstart/blob/master/README.md

I'm trying to import this package into the app: https://www.npmjs.com/package/arpad. I installed the package via npm update, my package.json dependencies look like this:

"dependencies": {
  "angular2": "2.0.0-beta.9",
  "systemjs": "0.19.24",
  "es6-promise": "^3.0.2",
  "es6-shim": "^0.35.0",
  "reflect-metadata": "0.1.2",
  "rxjs": "5.0.0-beta.2",
  "zone.js": "0.5.15",
  "arpad":"^0.1.2" <----- the package i'm trying to import
}

This is how the package exports its code:

module.exports = ELO;

I have a component importing the module like this:

import {ELO} from 'node_modules/arpad/index.js';

This is how systemJS is configured in the application's index.html:

  <script>
  System.config({
    packages: {        
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    },
    map:{'arpad':'node_modules/arpad'} <---- here 
  });
  System.import('node_modules/arpad/index.js'); <--- and here for good measure
  System.import('app/main')
        .then(null, console.error.bind(console));
</script>

Now, it looks a lot like I'm shooting in the dark, and that's exactly what the error messages in the application console had me doing. When I try to use the module in the component like this:

public elo = ELO;
constructor(){
    this.score = this.elo.expectedScore(200, 1000);
    ---- there is more to the component but this is the part where it breaks
}

I get the following message:

"ORIGINAL EXCEPTION: TypeError: this.elo is undefined"

So the question in a broader scope is:

How can I get a given npm package (that is not already an angular module) to work in a component or service using systemJS(or Webpack, or Browserify) as module loader in the ng2 quickstart?

Answer

Thierry Templier picture Thierry Templier · Mar 22, 2016

I have some comments here:

  • You should configure SystemJS this way for your module:

    System.config({
      map:{'arpad':'node_modules/arpad/index.js'}
      packages: {        
        app: {
          format: 'register',
          defaultExtension: 'js'
        }
      }
    });
    
  • You don't need to import your index.js file (see System.import('node_modules/arpad/index.js');) before importing your application (importing the app/main module).

  • You need to import your elo object this way:

    import * as Elo from 'arpad';
    
  • Then you should be able to use your module this way:

    constructor() {
      this.elo = new Elo();
      this.score = this.elo.expectedScore(200, 1000);
    }
    

Here is a plunkr describing this: https://plnkr.co/edit/K6bx97igIHpcPZqjQkkb?p=preview.