How to import lodash in angular 13 application level?

Viewed 40

I'm trying to import lodash in angular application level through main.ts like below.

//main.ts
import * as lodash from 'lodash';
declare global {
  const _: typeof lodash;
}

enter image description here

After adding above code, I can able to reference to the lodash and compiled successfully but in run time I was facing issue like below.

ERROR ReferenceError: _ is not defined

am I missing anything here? please help, thanks!

1 Answers

The following is one way to do that:

//main.ts
import * as lodash from 'lodash';

// This makes `_` available globally as a TS type:
declare global {
  const _: typeof lodash;
}

// And this makes `_` available globally as a JS object:
(window as any)['_'] = lodash;

// Or use this in case browser is not the only target platform:
(globalThis as any)['_'] = lodash;

Of course, this file should be imported before everything else.

Related