2

I am using lodash in my angular2 app. by using declare var _: any; i am doing lodash operation such as _.findIndex(...) . Now i am facing one issue. sometimes while loading page i am getting error as below

EXCEPTION: ReferenceError: _ is not defined

how to avoid this? As my assumption, lodash code is executed before declare var _: any;

Ramkrishna Sharma
  • 6,961
  • 3
  • 42
  • 51
Deepak
  • 1,373
  • 2
  • 10
  • 31

2 Answers2

2

In fact, it depends on the way to configure / include the lodash library into your HTML page:

  • Include the lodash.js file into a script element. This way, lodash is available as a global variable (_) into the application. In this case, you need to define it leveraging ambient declarations of TypeScript:

    declare var _: any;
    
  • Configure the lodash.js file into the SystemJS configuration. In this way, the lodash library will detect that it will be used within a module loader so it will register itself as a module and return the _ variable into exports. In this case, you need to use an import to get it. Since the _ variable is directly set into exports, you need to import it this way:

    import _ from 'lodash';
    

    The corresponding configuration would be:

    System.config({
      (...)
      map: {
        lodash: 'node_modules/lodash/lodash.js'
      },
      meta: {
        lodash: { format: 'amd' }
      }
    });
    
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Can't we use it directly with `` at the top of the component? – micronyks Mar 23 '16 at 08:30
  • In fact, `reference`s are only for compilation to import the contract of the library... It's not for runtime. – Thierry Templier Mar 23 '16 at 08:32
  • Still I'm not clear with it. look I have made this, http://plnkr.co/edit/3xEZBpwz6NCMU1uxBg5O?p=preview can you tell me what is wrong with it? I don't understand what do you mean by `runtime`? – micronyks Mar 23 '16 at 08:34
  • In your case, you included lodash within a script element so the `_` variable is directly available. Since you use the on-the-fly transpiling, you don't see the errors ;-) but with tsc, I guess that you will have some. You should add the `declare var _: any` and the ` – Thierry Templier Mar 23 '16 at 08:59
  • Oh I see. I have to check that. – micronyks Mar 23 '16 at 09:08
  • I am using this seed project [link](https://github.com/shivanshuag/angular2-seed). In this project there is no system.config. can you please explain how to do this? – Deepak Mar 23 '16 at 09:36
  • In my porject there is no systemjs how to fix this issue? – Deepak Apr 13 '16 at 06:36
1

If you are using TypeScript, then you need to import the library in your file:

import _ from 'lodash';

Have a look at a simular question: angular2 failing lodash import

Community
  • 1
  • 1