Importing individual lodash functions instead of whole lodash project

Two ways

There are two ways to do it:

  1. You can use packages with the individual functions and e.g. require('lodash.head')
  2. You can use the full package and e.g. require('lodash/head')

require('lodash.head')

You install the package with individual function:

npm install --save lodash.head

This adds this to package.json:

"dependencies": {
  "lodash.head": "^4.0.1"
}

You use it with:

var head = require('lodash.head');

require('lodash/head')

You install the full lodash package:

npm install --save lodash

This adds this to package.json:

"dependencies": {
  "lodash": "^4.17.4"
}

You use it with:

var head = require('lodash/head');

More examples

More complex example:

You can have _ with two functions that you need:

var head = require('lodash.head');
var tail = require('lodash.tail');
var _ = {pick, defaults};

Similar effect, different style:

var _ = {
  head: require('lodash.head'),
  tail: require('lodash.tail'),
};

Explanation

If you want only some part of lodash, like e.g. lodash.pick then use:

  • https://www.npmjs.com/package/lodash.pick

For more examples of single functions packaged as modules see:

  • https://www.npmjs.com/browse/keyword/lodash-modularized

You can also use custom builds, see:

  • https://lodash.com/custom-builds

When you use the full package and import only the functions that you need with:

var _ = {
  head: require('lodash/head'),
  tail: require('lodash/tail'),
};

Then some tools like Webpack may be able to optimize your build to include only the code that you actually use. When you import the entire lodash with:

var _ = require('lodash');

then static analysis cannot be sure which function will be used at runtime so it's harder to optimize well and usually more code is included in the build than is actually needed.


Using ES6 modules, this could be done like this as well:

import isEqual from 'lodash.isequal';

Reference