Lodash: Importing only what you need
Lodash is a super popular utility library, but pulling in the entire thing when you only need a single function - like shuffle
- is overkill. With modern bundlers like Vite, there are a few ways to keep your bundle size small.
Import styles matter
If you do this:
import _ from "lodash";
_.shuffle(array);
you're telling Vite (and Rollup under the hood) to grab the entire lodash library. That's ~70kb gzipped, even if you never touch debounce
, cloneDeep
, or any of the other helpers.
The right way
Instead, import just what you need:
import shuffle from "lodash/shuffle";
Now Rollup only includes the shuffle
function and its tiny dependencies. Much better.
An even better option: lodash-es
The lodash team also publishes lodash-es
. This is the exact same library, but distributed as ES modules.
Why does that matter? Because ES modules were designed with tree-shaking in mind. Tools like Rollup (which Vite uses in production builds) can safely drop any code you don't import.
As one StackOverflow thread puts it:
"CommonJS modules are not tree-shakable so you should definitely use
lodash-es, which is the Lodash library exported as ES Modules."
How to check your bundle
Want proof? Here are two easy ways:
-
Bundle visualizer
Install the rollup-plugin-visualizer and add it to yourvite.config.js
. After runningnpm run build
, you'll get a treemap showing exactly which parts of lodash made it in. -
Compare build sizes
Build your app twice:- once with
import _ from "lodash"
- once with
import shuffle from "lodash-es/shuffle"
Then compare the file sizes in your
dist/assets/
folder. You'll see the difference right away. - once with
Recap
import _ from "lodash"
→ whole libraryimport { shuffle } from "lodash"
→ whole libraryimport shuffle from "lodash/shuffle"
→ just shuffleimport shuffle from "lodash-es/shuffle"
→ best tree-shaking
support
If you only need one function, don't ship 70kb of utilities you'll never use. Import smart, and your users' devices will thank you.
Member discussion