通过 Angular-CLI 在 Angular 中包含和使用 NPM 库

Include and use NPM Libraries in Angular with Angular-CLI

我正在尝试在我的 Angular 2 应用程序中使用来自 npm 的 progressbar.js 库,该应用程序使用 Angular-CLI。

我用 npm install progressbar.js --save 安装了它。 progressbar.js 的文档说要将它与 var ProgressBar = require('progressbar.js') 一起使用,我不能使用它,因为我没有 SystemJS。

我搜索了一下,找到了一个解决方案,将其包含在 angular-cli.json 的脚本数组中,我这样做了:

"scripts": [
     "../node_modules/progressbar.js/dist/progressbar.js"
  ],

应用程序在 ng serve 下编译得很好,但我真的不知道如何使用包含的库。在我的组件中,我尝试了不同的导入语句,如 import * as Progressbar from 'progressbar.js/dist'import { Progressbar } from 'progressbar.js/dist' 但没有让它们中的任何一个工作。

有人知道我如何使用这个库吗?

由于 ProgressBar 未导出为 TypeScript class 您将无法使用 import 语句将其导入您的组件。

在angular-cli.json的scripts数组中包含progressbar.js文件后,在需要使用它的组件中添加如下行即可:declare var ProgressBar: any;。此语句是一种解决方法,可以在 TypeScript class.

中使用第三方 JavaScript 库

示例app.component.js - 简单地在控制台打印对象:

import { Component, OnInit } from '@angular/core';
declare var ProgressBar: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app works!';

  ngOnInit() {
    console.log(ProgressBar);
  }
}