angular 2 - adding 3rd party libs

后端 未结 8 1862
盖世英雄少女心
盖世英雄少女心 2020-11-28 09:22

I am trying to start using angular 2 cli.
I want to use momentjs in my project so here is what I have done:
1. created project using angular cli.
2. run np

8条回答
  •  悲哀的现实
    2020-11-28 09:45

    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)

    
    

    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 js folder. Then you have to reference js file in your index.html like this way:

    
    

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

提交回复
热议问题