Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve error "Cannot find name '_' " using lodash in angular2 app with webpack

Here's how I import lodash in typescript/angular2 app using webpack:

  • $ npm install lodash --save
  • $ typings install dt~lodash --save

In webpack.config.js:

module.exports = {
   plugins: [  
      new ProvidePlugin({
         '_' : 'lodash'

And it works.

But there's still an error in my editor (Sublime) and in the terminal on runtime : Cannot find name '_'

So, what I'm missing?

In the .ts file where i use lodash I tried to declare it like so:

declare var _ : LoDashStatic

with no luck.

like image 664
sebap Avatar asked Jul 28 '16 08:07

sebap


2 Answers

I had the same issue, this is what it work for me :

1 - This will declare lodash module to TypeScript can type check it for you.

typings install lodash --save

2 - In your .ts file you've to import lodash :

import * as _ from "lodash"

I hop it can help.

like image 98
HichamBI Avatar answered Nov 15 '22 06:11

HichamBI


I am not sure how old this issue is but these kind of issues are still happening. I have just added Lodash type definition into my Angular-CLI project and made it work. It was part of an experiment where I wanted some third party libraries to be used inside Angular2. I had to struggle a bit to figure out how it works so here it goes.

The current type definition for Lodash seems having some issue. So I am getting error while compiling. I replaced the content of type definition file with an older version of lodash type definition file and it worked. Working version is from the path,

https://github.com/borisyankov/DefinitelyTyped

I installed lodash with typings install dt~lodash --save

Once you add any type definition file, it will get a reference in the base type definition file as shown below.

Type definition base file

Now if you miss to refer the base file in tsconfig.json, we won't have the lodash module available in Angular2. You can add it as below,

enter image description here

To use the lodash feature import the module which you can see if you open the type definition file. In case of lodash it's "lodash".

In your components you can import the librabries like,

import * as $ from 'jquery';
import * as _ from "lodash";

and use the features in code,

Eg:

enter image description here

and the result is,

enter image description here

like image 35
Sanish Joseph Avatar answered Nov 15 '22 08:11

Sanish Joseph