Skip to content
Advertisement

How to Import a Single Lodash Function?

Using webpack, I’m trying to import isEqual since lodash seems to be importing everything. I’ve tried doing the following with no success:

JavaScript

Advertisement

Answer

You can install lodash.isequal as a single module without installing the whole lodash package like so:

JavaScript

When using ECMAScript 5 and CommonJS modules, you then import it like this:

JavaScript

Using ES6 modules, this would be:

JavaScript

And you can use it in your code:

JavaScript

Source: Lodash documentation

After importing, you can use the isEqual function in your code. Note that it is not a part of an object named _ if you import it this way, so you don’t reference it with _.isEqual, but directly with isEqual.

Alternative: Using lodash-es

As pointed out by @kimamula:

With webpack 4 and lodash-es 4.17.7 and higher, this code works.

JavaScript

This is because webpack 4 supports the sideEffects flag and lodash-es 4.17.7 and higher includes the flag (which is set to false).

Why Not Use the Version With the Slash? Other answers to this question suggest that you can also use a dash instead of a dot, like so:

JavaScript

This works, too, but there are two minor drawbacks:

  • You have to install the whole lodash package (npm install --save lodash), not just the small separate lodash.isequal package; storage space is cheap and CPUs are fast, so you may not care about this
  • The resulting bundle when using tools like webpack will be slightly bigger; I found out that bundle sizes with a minimal code example of isEqual are on average 28% bigger (tried webpack 2 and webpack 3, with or without Babel, with or without Uglify)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement