Bundle Size Issues Caused by Misusing Lodash

Highlights how default lodash imports pull in the full bundle, shows safer import patterns, and compares the savings from switching to lodash-es.

Dec 11, 2024 · 1 min read · 180 Words · -Views -Comments · Digital Life
JavaScript Performance 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

I spotted problematic lodash imports in a real project and wanted to document the fix.

The Problem

The project depended on the CommonJS build of lodash in package.json.

import _ from 'lodash';

import { cloneDeep } from 'lodash';

Regardless of the bundler, both patterns pull the entire library.

The Quick Fix

import cloneDeep from 'lodash/cloneDeep';

This only brings in cloneDeep. The downsides:

  1. Multiple functions mean multiple import lines.
  2. Those per-method modules are still CommonJS files that re-require other helpers, so extra code sneaks in anyway.

The Better Option

Lodash ships an ES module build. You can swap dependencies to lodash-es, or alias it without touching call sites:

{
  "lodash": "npm:lodash-es@^4.17.21"
}

Then import like this:

import { cloneDeep } from 'lodash-es';

Even with the ES module, avoid import _ from 'lodash-es'; that still drags in the whole bundle.

Size Difference After the Change

In testing, the optimized imports trimmed roughly 100 KB.

Before

https://static.1991421.cn/2024/2024-12-11-160835.jpeg

After

https://static.1991421.cn/2024/2024-12-11-161011.jpeg

Final Thoughts

The root of the size issue is that CommonJS modules are bundled wholesale, whereas ES modules let your tooling tree-shake away the unused code.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover