【问题标题】:Importing lodash functions globally in Angular 4 app在 Angular 4 应用程序中全局导入 lodash 函数
【发布时间】:2018-03-06 11:17:18
【问题描述】:

我正在尝试通过将 lodash 函数全局导入到 app.module.ts 来优化我的 Angular 4 应用程序。我试过了:

import { some } from 'lodash/fp/some';
import _ from 'lodash/wrapperLodash';

但是,我无法在组件中获取对该函数的引用。这将引发错误:

_.some(myVar, { lat: null });

我的依赖(与主题相关的):

"devDependencies": {
"@angular/compiler": "^4.2.4",
"@angular/core": "^4.2.4",
"@types/lodash": "^4.14.104",
"lodash": "^4.17.5",
"typescript": "~2.3.3"
}

错误:

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_0_lodash_fp_wrapperLodash___default.a.some is not a function

【问题讨论】:

  • 从 'lodash' 导入 * 作为 _;在这种情况下,'lodash' 将是 npm 包
  • 这样你就导入了整个包。我想要实现的是减少我的供应商捆绑包的大小。
  • 啊,所以你想具体一点,只带一些进来,够公平的。
  • 好的。所以我得到了一种错误
    lodash_wrapperLodash___default.a.find is not a function
  • 如果你只想要'some',你应该这样做: import { some } from 'lodash';

标签: javascript angular lodash


【解决方案1】:

我仍然不明白为什么人们使用 lodash 来实现 ES6 已经拥有的所有可能性。

https://www.sitepoint.com/lodash-features-replace-es6/

但是如果你想使用它,试着用这种方式导入:

import * as _ from "lodash";

从“lodash”导入*作为_; 请注意,如果您使用 import _ from “lodash”,您将收到以下错误“模块‘lodash’有 没有默认导出”:

来自https://hassantariqblog.wordpress.com/2016/10/15/angular2-import-lodash-into-angular2-application-using-typescript/

或者只是lodash的一个功能:

import wrapperLodash from 'lodash/wrapperLodash';

【讨论】:

  • 不幸的是,这是要导入整个库。我只需要导入特定的功能并且需要在全局范围内执行(仅一次)。
  • 试试这个 'import wrapperLodash from 'lodash/wrapperLodash';'
  • '_' 指的是一个 UMD 全局,但当前文件是一个模块。考虑改为添加导入。
  • 完全是……这个话题没有人回答。
猜你喜欢
  • 2022-01-27
  • 1970-01-01
  • 2017-12-28
  • 2022-07-06
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多