Correct way of importing and using lodash in Angular

前端 未结 5 1783
再見小時候
再見小時候 2020-12-13 17:27

I used to be able to use a lodash method in Angular by an import statement that looked like the following:

import {debounce as _debounce} from \'lodash\';
         


        
5条回答
  •  忘掉有多难
    2020-12-13 18:13

    Importing lodash or any javascript library inside angular:

    step-1: Install the libarary(lodash)

    npm i --save lodash
    

    step-2: import it inside the component and use it.

    import it as follow:

    import 'lodash';
    
    declare var _:any;
    

    or

    import * as _ from 'lodash';
    

    Step-3: Install type definitions for Lo-Dash (it's optional)

    npm install --save-dev @types/lodash
    

    see the example if you still have doubts

    import { Component, OnInit } from '@angular/core';
    // import * as _ from 'lodash';
    import 'lodash';
    
    declare var _:any;
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      title = 'test-lodash';
    
      ngOnInit() {
        console.log(_.chunk(['a', 'b', 'c', 'd'], 2)); //lodash function
        console.log(_.random(1, 100)); //lodash function
      }
    
    }
    

提交回复
热议问题