3

I am trying to use the progressbar.js library from npm in my Angular 2 application which uses Angular-CLI.

I installed it with npm install progressbar.js --save. The documentation of progressbar.js says to use it with var ProgressBar = require('progressbar.js'), which I can't use because I don't have SystemJS.

I searched a bit and found a solution to include it in the scripts array of the angular-cli.json, which I did:

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

The application compiles fine with ng serve, but I really couldn't figure how to make use of the included library. In my component I tried different import statements like import * as Progressbar from 'progressbar.js/dist' or import { Progressbar } from 'progressbar.js/dist' but didn't get any of them to work.

Does anyone know how I can use this library?

1 Answer 1

3

Since ProgressBar is not exported as a TypeScript class you will not be able to use the import statement to import it into your component.

After including the progressbar.js file in the scripts array of angular-cli.json, it enough to add the following line in the components where you need to use it: declare var ProgressBar: any;. This statement is a workaround which enables using third party JavaScript libraries in a TypeScript class.

Example app.component.js - simply printing the object in the console:

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I tried it and it works... Just trying to understand now how I can figure out which variable name to declare for an abitrary library. Obviously ProgressBar in this case is an easy guess but I'm sure there is a better way then guessing... Was just now looking through some files in the node_modules but could find an obvious declaration, export, configuration, ...
@DanielLerps Usually these JavasScript libraries add a reference to an object (ProgressBar in your case) to either the window or the global object. If you open up the progressbar.js file you can see how this reference is added, although the code is not very readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.