Reputation: 1433
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;
Upvotes: 2
Views: 1475
Reputation: 202196
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' }
}
});
Upvotes: 2
Reputation: 275
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
Upvotes: 1