r_31415
r_31415

Reputation: 8982

Import single function from lodash in Angular 2 + webpack project

A very common question.

How do you import a single function from lodash?

I tried lodash.orderby, but I believe that is supposed to be used with commonjs. I also tried lodash-es without much success. I still get a variety of errors such as Cannot find module 'lodash-es' or Cannot find module 'lodash/orderBy'.

Another possibility was to use custom builds, but I couldn't figure out how to import a single function correctly.

Running Angular 2 RC-4, typescript 2.1.0-dev, webpack 2 (beta).

Typescript is configured in the following way:

{
  "compilerOptions": {
    "target": "es5",
    "module": "es6",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

UPDATE

I'm currently importing the module in the following way:

import {orderBy} from 'lodash-es';

This is actually working (that is, the app is using orderBy correctly), but the error persists. I believe the issue is that there are no type definition for lodash-es.

typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160505161446",
    "jquery": "registry:dt/jquery#1.10.0+20160417213236",
    "node": "registry:dt/node#6.0.0+20160613154055",
    "typeahead": "registry:dt/typeahead#0.11.1+20160317120654"
  },
  "dependencies": {
    "lodash": "registry:npm/lodash#4.0.0+20160416211519"
  }
}

UPDATE:

This is an old question, but for future reference, if you're not using require, you might need to install the correct typing information. In this particular case, I needed to install and declare the module lodash-es.

Upvotes: 1

Views: 987

Answers (1)

sax
sax

Reputation: 838

Install the function required:

npm install --save lodash.countby @types/lodash.countby

Then import it using:

const countBy = require('lodash.countBy');

Upvotes: 1

Related Questions