Angular2: Import Lodash into Angular2 application using Typescript

Standard

Follow below steps to add lodash into your Angular2 app using Typescript 2.0.

Please note I am using Typescript 2.0 and Angular 2.0

Step 1:

Include lodash as the dependencies in package.json file by CMD

> npm install --save lodash

Step 2:

Include lodash typings as the dev dependencies in package.json file by CMD for Typescript otherwise you will get error in Visual Studio/Visual Code that “Cannot find module ‘lodash’

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

After above commands your package.json will be updated as below:

screenshot_1

Step 3:

As I am using systemJS to load module, so Update the systemjs.config.js file to map lodash. This file provides information to a module loader about where to find application modules, and registers all the necessary packages.

map: {
        'lodash': 'npm:lodash'
     },
        
packages: {
            lodash: {
                main: 'index.js',
                defaultExtension: 'js'
            }
          }

Step 4:

Import lodash in your angular component.

import * as _ from "lodash";

Please note that If you use import _ from “lodash”, you will receive following error that “Module ‘lodash’ has no default export”:

screenshot_3

Step 5:

Use lodash in your code as per need just like below as I am using _.isEqual(a,b) and IntelliSense is working fine:

screenshot_4

Update:

Lot of things have been changed since Angular2 RTM, I was having issues like “cannot find namespace ‘_’ and Cannot find name ‘many’ ”

Solution: Update @types/lodash in package.json to Typescript 2.0 compatible types in order to use lodash without any issue

"@types/lodash": "ts2.0"

Visit this link for complete solution:

Cannot find name ‘many’ and namespace ‘_’ issues with Lodash in Angular2 application using Typescript

 

Cheers. Happy Coding.

Advertisements

4 thoughts on “Angular2: Import Lodash into Angular2 application using Typescript

    • Hi

      You are right about that rather than import the whole library which is about 100k, its better to load just in need methods, I hope below sample code serves the need.

      import { toLower } from “lodash”;

      let alias = toLower(“Machtyn”);

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s