Manuel Manuel - 3 months ago 132
TypeScript Question

3rd Party Libraries in Angular CLI wich are not on npm

I'm currently transferring an app from commen Angular 2 to Angular CLI

Now I'm trying to figure out how to import 3rd party libraries like orbitcontrols.js which aren't on

npm
or
bower
to my app.

I found out on https://github.com/angular/angular-cli/wiki/3rd-party-libs that it seems not to be hard to import libraries which are supported by
npm
.


  • How is it with other libraries?

  • Is it possible at all?



Versions:

angular-cli 1.0.0-beta.9

Answer

Mostly yes, but it depends on the library uses too. Still Angular-cli has some problem with the 3rd party library integration. Until They fix it properly, I can give you a hack around. Lets say you want to use _ of lodash in your code. So I will give you my working code scenario-

To install lodash

npm install lodash --save
typings install lodash --ambient --save

before that make sure you install typings globally

npm install typings -g

Then in your angular-cli-build.json , make sure it remains like this way

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      ...
      'lodash/**/*.js'
    ]
  });
};

and in your system-config.ts:

/** Map relative paths to URLs. */
 const map: any = {
   'lodash': 'vendor/lodash/lodash.js'
 };

 /** User packages configuration. */
 const packages: any = {
   'lodash': {
     format: 'cjs'
   }
 };

in your src/index.html add this line(This is the weird fix)

<script src="/vendor/lodash/lodash.js" type="text/javascript"></script>

now in your component where you want to use lodash , write this way

declare var _:any;

@Component({
})
export class YourComponent {
  ngOnInit() {
     console.log(_.chunk(['a', 'b', 'c', 'd'], 2));
  }
}

it worked for me :). I have used enormous 3rd party libraries in my angular2 project through angular-cli. Hope it will help you too

Edit:

If you dont get any npm for your third-party libraries. Make an assets folder under your src folder. Then you can add separate folders for js,css and images. Put your third-party js inside the jsfolder. Then you have to reference js file in your index.html like this way:

<script src="assets/js/your_js.js"></script>

Now, when you do ng build or ng serve it will automatically update the public folder with your assets/js. Hope you understand the whole scenario :)