首页 文章

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

提问于
浏览
3

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

我用 npm install progressbar.js --save 安装了它 . progressbar.js的文档说它与 var ProgressBar = require('progressbar.js') 一起使用,我可以__9646476没有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' ,但没有让它们中的任何一个工作 .

有谁知道如何使用这个库?

1 回答

  • 3

    由于ProgressBar未导出为TypeScript类,因此您将无法使用 import 语句将其导入组件 .

    在angular-cli.json的scripts数组中包含progressbar.js文件后,足以在需要使用它的组件中添加以下行: declare var ProgressBar: any; . 此语句是一种解决方法,可以在TypeScript类中使用第三方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);
      }
    }
    

相关问题