1

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!

7
  • Out of curiosity, why are you adding the above code in your main.ts file? Commented Sep 9, 2022 at 14:22
  • Thanks for the comment @Andres2142 , I thought main.ts is the root file in bootstrapping process, so if I can declare the variable here we can access application level without re-import again and again. Commented Sep 9, 2022 at 14:28
  • Interesting, I haven't tried that myself, I can suggest installing @types/lodash so you have auto-completion, and then just import lodash in every file you need. Commented Sep 9, 2022 at 15:35
  • I did not try this approach, but I think it should work. Try something like (window as any)['_'] = lodash in you main.ts. With declare you added type of global _ everywhere, and with that window property assignment you add actual value to be used in any context. Commented Sep 10, 2022 at 8:55
  • 1
    Thanks @alx , It is working after adding (window as any)['_'] = lodash Or (globalThis as any)['_'] = lodash Commented Sep 12, 2022 at 7:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.