如何在angular2组件中导入npm包?

时间:2016-03-22 13:29:43

标签: angular webpack browserify systemjs

我试图学习ng2的绳索,依赖注射系统正在扼杀我。

我正在使用ng快速入门: https://github.com/angular/quickstart/blob/master/README.md

我尝试将此软件包导入应用:https://www.npmjs.com/package/arpad。我通过npm update安装了包,我的package.json依赖项看起来像这样:

"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
}

这是包导出其代码的方式:

module.exports = ELO;

我有一个组件导入模块,如下所示:

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

这就是在应用程序的index.html中配置systemJS的方法:

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

现在,它看起来很像我在黑暗中拍摄,这正是应用程序控制台中的错误信息让我做的事情。当我尝试在组件中使用这样的模块时:

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
}

我收到以下消息:

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

所以更广泛的问题是:

如何在ng2快速入门中使用systemJS(或Webpack或Browserify)作为模块加载器在组件或服务中使用给定的npm包(不是角度模块)?

1 个答案:

答案 0 :(得分:5)

我在这里有一些评论:

  • 您应该以这种方式为您的模块配置SystemJS:

    System.config({
      map:{'arpad':'node_modules/arpad/index.js'}
      packages: {        
        app: {
          format: 'register',
          defaultExtension: 'js'
        }
      }
    });
    
  • 在导入应用程序之前,您无需导入index.js文件(请参阅System.import('node_modules/arpad/index.js');)(导入app/main模块)。

  • 您需要以这种方式导入elo对象:

    import * as Elo from 'arpad';
    
  • 然后您应该能够以这种方式使用您的模块:

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

这是一个描述这个问题的傻瓜:https://plnkr.co/edit/K6bx97igIHpcPZqjQkkb?p=preview

相关问题