28

I have previously used lodash in my Angular 4 application by simply importing it and using it as shown here:

import lodash from 'lodash';

public getSubtotal() : number {
  return lodash.sumBy(this.cartItems, function(item) {        
    return item.product.price * item.item.quantity;
  })

}

I am once again trying to use lodash similarly but am getting an error that lodash is undefined.

import lodash from 'lodash';

lodash.indexOf([1, 2, 1, 2], 2);

I get the following error:

ERROR TypeError: Cannot read property 'indexOf' of undefined
at CustomizeComponent.showTopping (customize.component.ts:39)
at Object.eval [as updateDirectives] (CustomizeComponent.html:285)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14638)
at checkAndUpdateView (core.js:13785)
at callViewAction (core.js:14136)
at execComponentViewsAction (core.js:14068)
at checkAndUpdateView (core.js:13791)
at callViewAction (core.js:14136)
at execEmbeddedViewsAction (core.js:14094)
at checkAndUpdateView (core.js:13786)
koque
  • 1,830
  • 5
  • 28
  • 49

1 Answers1

59

First you need to install the packages lodash and @types/lodash (contains type definitions):

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

Then you can use lodash e.g. with import * as _ from 'lodash'; and further do _.indexOf([1, 2, 1, 2], 2);

You could also do import * as _isEmpty from 'lodash/isEmpty'; (thanks to joshrathke) or import {isEmpty} from 'lodash';

pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • 7
    For what its worth directly importing only the modules you need can make your build significantly smaller. Signifigantly, relative to the Lodash library :) `import * as _indexOf from 'lodash/indexOf'; – joshrathke Feb 16 '18 at 23:22
  • 1
    @joshrathke That's a good point. I will edit my answer to add this point. – pzaenger Feb 16 '18 at 23:23
  • Worked perfectly. Thank you. – koque Feb 16 '18 at 23:39
  • 2
    @pzaenger `import * as _isEmpty from 'lodash/isEmpty';` does not work. Says `This module can only be referenced with ECMAScript...` – Rich May 02 '19 at 02:40
  • 2
    @Rich - Give this a try instead - import { isEmpty as _isEmpty } from 'lodash' – thiag0 Feb 10 '20 at 18:29
  • Building on both the import style suggested by @joshrathke and the bracket syntax in the answer, my favorite method is `import { isEmpty as _isEmpty, cloneDeep as _cloneDeep } from 'lodash';` It's the best of both worlds. You can rename the lodash modules and you don't need knowledge of the internal structure of lodash. I showed multiple lodash modules for good measure :-). Edit: just saw @thiag0 answer, which is the same thing lol. Well this at least shows importing multiple modules ¯\\_(ツ)_/¯ – mogelbuster Feb 16 '21 at 22:27