How to import npm package into angular2 component?

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

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

I am trying to import this package into an application: https://www.npmjs.com/package/arpad . I installed the package through an 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 a package exports its code:

 module.exports = ELO; 

I have a component importing a module as follows:

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

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

  <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 very similar to what I am shooting in the dark, and exactly what they wrote me error messages in the application console. When I try to use a module in a component as follows:

 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 is in a wider context:

How can I get a given npm package (which is not yet an angular module) to work in a component or service using systemJS (or Webpack or Browserify) as a module loader in ng2 quick start?

+7
angular webpack systemjs browserify
source share
1 answer

I have some comments here:

  • You must configure SystemJS in this way for your module:

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

  • You need to import the elo object this way:

     import * as Elo from 'arpad'; 
  • Then you will need to use your module as follows:

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

Here is the plunkr description: https://plnkr.co/edit/K6bx97igIHpcPZqjQkkb?p=preview .

+4
source share

All Articles