问题
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;
回答1:
In fact, it depends on the way to configure / include the lodash library into your HTML page:
Include the lodash.js file into a
scriptelement. 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' } } });
回答2:
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
来源:https://stackoverflow.com/questions/36171727/lodash-in-angular2-declare-var-any-not-working