How you can trim down your bundles by importing lodash properly

Dana Hartweg
Sep 1, 2017 · 2 min read
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.

Inside Formstack

Experiences, opinions and shared thoughts on design, development, product management, business, and tech. By the makers of Formstack.

Dana Hartweg

Written by

Senior Front End Software Engineer, InVision Studio

Inside Formstack

Experiences, opinions and shared thoughts on design, development, product management, business, and tech. By the makers of Formstack.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade