Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Correct way of importing and using lodash in Angular

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

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:

Angular: 2.4.5

Typescript: 2.1.5

Angular-cli: 1.0.0-beta.26

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(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'

or

import { debounce } from "lodash";

Use it as:

debounce()

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

npm install [email protected] --save-dev

UPDATE:

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...