Importing Lodash into Angular2 + Typescript Application

Importing lodash into angular2 + typescript application

Here is how to do this as of Typescript 2.0:
(tsd and typings are being deprecated in favor of the following):

$ npm install --save lodash

# This is the new bit here:
$ npm install --save-dev @types/lodash

Then, in your .ts file:

Either:

import * as _ from "lodash";

Or (as suggested by @Naitik):

import _ from "lodash";

I'm not positive what the difference is. We use and prefer the first syntax. However, some report that the first syntax doesn't work for them, and someone else has commented that the latter syntax is incompatible with lazy loaded webpack modules. YMMV.

Edit on Feb 27th, 2017:

According to @Koert below, import * as _ from "lodash"; is the only working syntax as of Typescript 2.2.1, lodash 4.17.4, and @types/lodash 4.14.53. He says that the other suggested import syntax gives the error "has no default export".

Correct way of importing and using lodash in Angular

(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 typescript@2.0.10 --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'

How to import lodash in angular 13 application level?

The following is one way to do that:

//main.ts
import * as lodash from 'lodash';

// This makes `_` available globally as a TS type:
declare global {
const _: typeof lodash;
}

// And this makes `_` available globally as a JS object:
(window as any)['_'] = lodash;

// Or use this in case browser is not the only target platform:
(globalThis as any)['_'] = lodash;

Of course, this file should be imported before everything else.

Using lodash in Angular 4

First you need to install the packages lodash and @types/lodash (contains type definitions):

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

Then you can use lodash e.g. with import * as _ from 'lodash'; and further do _.indexOf([1, 2, 1, 2], 2);

You could also do import * as _isEmpty from 'lodash/isEmpty'; (thanks to joshrathke) or import {isEmpty} from 'lodash';



Related Topics



Leave a reply



Submit