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

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

问题描述

过去,我可以通过如下所示的import语句在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().这是唯一(和/或正确)的方法吗?有没有办法只导入去抖动,还是由于摇晃"而没有关系?我意识到我可以编写自己的去抖动功能,但是我主要对正确"的功能感兴趣.做到这一点的方法.

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.我尝试过的其他变体(每个变体都与之相关的某种错误):

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

Angular: 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()

顺便说一句::在使用angular 2.x时,您可能必须将打字稿版本降级为2.0.10.

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天全站免登陆