在 Angular 中导入和使用 lodash 的正确方法 [英] Correct way of importing and using lodash in Angular

查看:34
本文介绍了在 Angular 中导入和使用 lodash 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经能够通过如下所示的导入语句在 Angular 中使用 lodash 方法:

I used to be able to use a lodash method in Angular by an import statement that looked like the following:

import {debounce as _debounce} from 'lodash';

我现在在使用该语句时收到以下错误:

I now get the following error when using that statement:

'"{...}/node_modules/@types/lodash/index"' has no exported member 'debounce'.

唯一可以编译没有错误的是这个语句:

The only thing that will compile without errors is this statement:

import * as _ from 'lodash'; 

在我的代码中,我将 _debounce() 更改为 _.debounce().这是唯一(和/或正确)的方法吗?有没有办法只导入去抖动,或者由于treeshaking"而无关紧要?我意识到我可以编写自己的去抖动函数,但我主要对正确"感兴趣.方法来做到这一点.

In my code, I change _debounce() to _.debounce(). Is that the only (and/or correct) way to do it? Is there a way to only import debounce, or does it not matter due to "treeshaking"? I realize I can write my own debounce function, but I'm mainly interested in the "right" way to do this.

附言我尝试过的其他变体(每个变体都有某种与之相关的错误):

p.s. Other variations that I've tried (each has some sort of error associated with it):

import {debounce as _debounce } from 'lodash/debounce';
import * as _debounce from 'lodash/debounce';
import debounce = require('lodash/debounce');

仅供参考...我正在使用以下版本:

FYI...I'm using the following versions:

角度:2.4.5

打字稿:2.1.5

Angular-cli: 1.0.0-beta.26

Angular-cli: 1.0.0-beta.26

推荐答案

(如果您关心摇树,请参阅更新)
我想为了将 lodash 带入你已经完成的项目

(if you care about tree shaking see update)
I suppose in order to bring lodash in to your project you already done

npm install lodash --save
npm install @types/lodash --save-dev

如果您只想导入所需的功能,您应该这样做:

If you want to import just required functions you should do:

import * as debounce from 'lodash/debounce'

import { debounce } from "lodash";

将其用作:

debounce()

顺便说一句:您可能需要将打字稿版本降级到 2.0.10,因为您使用的是 angular 2.x.

BTW: You might have to downgrade your typescript version to 2.0.10 as you are using angular 2.x.

npm install typescript@2.0.10 --save-dev

更新:

最近我意识到 lodash 包不能摇树,所以如果你需要摇树只需使用 lodash-es 代替.

Recently I realised that lodash package is just not tree shakable, so if you need tree shaking just use lodash-es instead.

npm install lodash-es --save
npm install @types/lodash-es --save-dev

import debounce from 'lodash-es/debounce'

这篇关于在 Angular 中导入和使用 lodash 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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