Correct way of importing and using lodash in Angular

前端 未结 5 1782
再見小時候
再見小時候 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:19

    (if you care about tree shaking see update)
    I suppose in order to bring lodash in to your project you already done

    npm install lodash --save
    npm install @types/lodash --save-dev
    

    If you want to import just required functions you should do:

    import * as debounce from 'lodash/debounce'
    

    or

    import { debounce } from "lodash";
    

    Use it as:

    debounce()
    

    BTW: You might have to downgrade your typescript version to 2.0.10 as you are using angular 2.x.

    npm install typescript@2.0.10 --save-dev
    

    UPDATE:

    Recently I realised that lodash package is just not tree shakable, so if you need tree shaking just use lodash-es instead.

    npm install lodash-es --save
    npm install @types/lodash-es --save-dev
    
    import debounce from 'lodash-es/debounce'
    

提交回复
热议问题