Bundle Size Issues Caused by Misusing Lodash

Bundle Size Issues Caused by Misusing Lodash

12月 11, 2024 · 1 分钟阅读时长 · 180 字 · -阅读 -评论

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.

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源