Lodash in angular2, declare var_:any not working

陌路散爱 提交于 2019-12-01 08:04:51

问题


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 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' }
      }
    });
    



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!