Lodash在angular2声明var_:任何不工作 [英] Lodash in angular2, declare var_:any not working

查看:145
本文介绍了Lodash在angular2声明var_:任何不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用我angular2应用lodash。通过使用宣布VAR _:​​任何我在做lodash操作,如 _ findIndex(...)。现在我面临的一个问题。有时在加载页面我得到如下错误

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

如何避免这种情况?
正如我的假设,lodash code为前执行申报VAR _:​​任何

推荐答案

在事实上,这取决于方式来配置/包括lodash库到你的HTML页面:

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


  • 提供lodash.js文件到一个剧本元素。通过这种方式,lodash可以作为一个全局变量( _ )到应用程序。在这种情况下,你需要定义它利用打字稿的环境声明:

  • 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;


  • 配置lodash.js文件到SystemJS配置即可。以这种方式,在lodash库将检测其将一个模块加载内使用,因此将其自身注册为一个模块并返回 _ 可变进出口。在这种情况下,你需要使用进口来得到它。因为 _ 变量直接设置成出口,你需要导入这种方式:

  • 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';
    

    对应的配置是:

    System.config({
      (...)
      map: {
        lodash: 'node_modules/lodash/lodash.js'
      },
      meta: {
        lodash: { format: 'amd' }
      }
    });
    


  • 这篇关于Lodash在angular2声明var_:任何不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆