Lodash in angular2, declare var_:any not working

前端 未结 2 406
清歌不尽
清歌不尽 2021-01-15 15:25

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

相关标签:
2条回答
  • 2021-01-15 15:42

    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

    0 讨论(0)
  • 2021-01-15 16:03

    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' }
        }
      });
      
    0 讨论(0)
提交回复
热议问题