Gopi Raju
Gopi Raju

Reputation: 239

How to import lodash in angular 13 application level?

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!

Upvotes: 1

Views: 1944

Answers (1)

alx
alx

Reputation: 2367

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.

Upvotes: 1

Related Questions