Friends don’t let friends import lodash incorrectly

How you can trim down your bundles by importing lodash properly

Dana Hartweg
Inside Formstack
2 min readSep 1, 2017

--

Importing lodash correctly in a Webpack project

Overview

Webpack is an amazing module bundler, but it’s not without its complexities. If you’re just getting started, everything can seem to just work by magic… much like when you’re getting started with AngularJS and the DOM updates automatically for the first time. Below is one simple tip to dramatically decrease your final bundle size if you’re using lodash.

Using lodash with Webpack

If you’re using lodash as your javascript utility library, you’re likely not using a fraction of the provided methods. This is exactly the use-case for Webpack, picking and choosing modules of code that you need.

You do some searching and find there is a lodash module optimized for module bundlers! You find lodash-es on npm, and it immediately seems to solve your problem. You import { merge } from 'lodash-es'; and you’re off to the races!

Hold your horses, though! If you’re paying attention to your builds, you notice a HUGE increase in both time to complete and final size. What gives?!

As is common with modules on npm, the main entry point simply imports internal methods and exports them… you can see that in action in the lodash-es source. While this is a convenience, Webpack currently has no means to tree-shake a module like lodash-es without assistance from separate babel plugins, or other transformations in your pipeline.

The easy solution

The easiest solution to correcting the problem? Simply change your import statement:

👎 import { merge } from ‘lodash-es’;

👍 import merge from ‘lodash-es/merge’;

When the main entry point for lodash isn’t referenced, Webpack no longer bundles all of those modules you aren’t using. (If you’re using typescript, it looks like there may be some additional hurdles for you.)

What you gain

Only using a handful of lodash utilities, we removed nearly 300kB (before gzipping) from our production bundles at Formstack. The inefficient import was indeed deployed for a while before we caught it and we’re now, more than ever, very aware of what makes it into our production builds.

--

--