Skip to content Skip to sidebar Skip to footer

Importing Lodash Into Angular2 + Typescript Application

I am having a hard time trying to get the lodash modules imported. I've setup my project using npm+gulp, and keep hitting the same wall. I've tried the regular lodash, but also lod

Solution 1:

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".

Solution 2:

Update September 26, 2016:

As @Taytay's answer says, instead of the 'typings' installations that we used a few months ago, we can now use:

npm install --save@types/lodash

Here are some additional references supporting that answer:

If still using the typings installation, see the comments below (by others) regarding '''--ambient''' and '''--global'''.

Also, in the new Quick Start, config is no longer in index.html; it's now in systemjs.config.ts (if using SystemJS).

Original Answer:

This worked on my mac (after installing Angular 2 as per Quick Start):

sudo npm install typings --global
npm install lodash --save 
typings install lodash --ambient--save

You will find various files affected, e.g.

  • /typings/main.d.ts
  • /typings.json
  • /package.json

Angular 2 Quickstart uses System.js, so I added 'map' to the config in index.html as follows:

System.config({
    packages: {
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    },
    map: {
      lodash: 'node_modules/lodash/lodash.js'
    }
  });

Then in my .ts code I was able to do:

import _ from'lodash';

console.log('lodash version:', _.VERSION);

Edits from mid-2016:

As @tibbus mentions, in some contexts, you need:

import * as _ from'lodash';

If starting from angular2-seed, and if you don't want to import every time, you can skip the map and import steps and just uncomment the lodash line in tools/config/project.config.ts.

To get my tests working with lodash, I also had to add a line to the files array in karma.conf.js:

'node_modules/lodash/lodash.js',

Solution 3:

First things first

npm install --save lodash

npm install -D @types/lodash

Load the full lodash library

//some_module_file.ts// Load the full library...import * as _ from'lodash'// work with whatever lodash functions we want
_.debounce(...) // this is typesafe (as expected)

OR load only functions we are going to work with

import * as debounce from'lodash/debounce'//work with the debounce function directlydebounce(...)   // this too is typesafe (as expected)


UPDATE - March 2017

I'm currently working with ES6 modules, and recently i was able to work with lodash like so:

// the-module.js (IT SHOULD WORK WITH TYPESCRIPT - .ts AS WELL) // Load the full library...import _ from'lodash'// work with whatever lodash functions we want
_.debounce(...) // this is typesafe (as expected)
...

OR import specific lodash functionality:

import debounce from'lodash/debounce'//work with the debounce function directlydebounce(...)   // this too is typesafe (as expected)
...

NOTE - the difference being * as is not required in the syntax


References:

enter image description here

Good Luck.

Solution 4:

Step 1: Modify package.json file to include lodash in the dependencies.

"dependencies": {
"@angular/common":  "2.0.0-rc.1",
"@angular/compiler":  "2.0.0-rc.1",
"@angular/core":  "2.0.0-rc.1",
"@angular/http":  "2.0.0-rc.1",
"@angular/platform-browser":  "2.0.0-rc.1",
"@angular/platform-browser-dynamic":  "2.0.0-rc.1",
"@angular/router":  "2.0.0-rc.1",
"@angular/router-deprecated":  "2.0.0-rc.1",
"@angular/upgrade":  "2.0.0-rc.1",
"systemjs": "0.19.27",
"es6-shim": "^0.35.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12",
"lodash":"^4.12.0",
"angular2-in-memory-web-api": "0.0.7",
"bootstrap": "^3.3.6"  }

Step 2:I am using SystemJs module loader in my angular2 application. So I would be modifying the systemjs.config.js file to map lodash.

(function(global) {

// map tells the System loader where to look for thingsvar map = {
    'app':                        'app', // 'dist','rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular',
    'lodash':                    'node_modules/lodash'
};

// packages tells the System loader how to load when no filename and/or no extensionvar packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
    'lodash':                    {main:'index.js', defaultExtension:'js'}
};

var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
];

// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});

var config = {
    map: map,
    packages: packages
}

// filterSystemConfig - index.html's chance to modify config before we register it.if (global.filterSystemConfig) { global.filterSystemConfig(config); }

System.config(config);})(this);

Step 3: Now do npm install

Step 4: To use lodash in your file.

import * as _ from'lodash';
let firstIndexOfElement=_.findIndex(array,criteria);

Solution 5:

Since Typescript 2.0, @types npm modules are used to import typings.

# Implementation package (required to run)$ npm install --save lodash

# Typescript Description$ npm install --save @types/lodash 

Now since this question has been answered I'll go into how to efficiently import lodash

The failsafe way to import the entire library (in main.ts)

import'lodash';

This is the new bit here:

Implementing a lighter lodash with the functions you require

import chain from"lodash/chain";
import value from"lodash/value";
importmapfrom"lodash/map";
import mixin from"lodash/mixin";
import _ from"lodash/wrapperLodash";

source: https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba#.kg6azugbd

PS: The above article is an interesting read on improving build time and reducing app size

Post a Comment for "Importing Lodash Into Angular2 + Typescript Application"