How-To Guide

How to Shrink Your JavaScript Bundle

Analyse what is in the bundle, remove or replace the heavy dependencies, enable tree shaking, and set a budget so it stays small.

On this page

  1. Introduction
  2. How Bundles Grow
  3. Analysing the Bundle
  4. Finding the Bloat
  5. Tree Shaking and Side Effects
  6. Removing and Replacing Dependencies
  7. Setting a Budget
  8. Conclusion

Introduction

JavaScript is the most expensive resource a page loads, because the browser must download, parse and execute it before the page is interactive, and execution competes with rendering for the main thread. A bundle that has quietly grown to a megabyte, mostly from dependencies the page barely uses, is the common cause of a slow site, and the growth is gradual enough that no single change looks wrong. Shrinking it is a loop: analyse what is in the bundle, find the largest contributors, remove or replace or lazy-load them, and watch the size as you go. This article covers the analysis, the common offenders, tree shaking, and setting a budget.

How Bundles Grow

Bundles grow through dependencies: a utility library imported wholesale for one function, a moment-like date library with locales, a component library that includes every component, a polyfill for a browser nobody uses. Each seems small when added and the total becomes the largest asset on the page. Because the growth is gradual, no single decision looks wrong, which is why the analysis is the starting point.

Duplication is another cause: the same library at two versions, or a dependency bundled both into a shared chunk and a route chunk. A bundler that does not deduplicate can ship the same code twice, which the analysis reveals.

Analysing the Bundle

A bundle analyser produces a map of the output with each module’s size, which turns the bundle into a list of offenders sorted by size. Generate it for the production build, because development builds include code that is stripped in production. Look at the largest modules and, for each, whether the page uses it and whether a smaller alternative exists.

# Produce a treemap of the production bundle and open it in the browser.
npx source-map-explorer 'dist/assets/*.js'
# or, with a bundler plugin:
npx vite-bundle-visualizer

# Check gzip size, which is what the network actually transfers.
gzip -c dist/assets/index.js | wc -c

# See whether a dependency is duplicated across chunks.
npx esbuild-visualizer --metadata dist/meta.json --open

Finding the Bloat

The usual offenders are date libraries with all locales, lodash imported as a whole, icon packages imported as a whole, a component library that is not tree-shakeable, and polyfills. For each, check whether the page uses more than a small part; if not, import only the part, replace the library, or lazy-load it.

A single heavy dependency used on one route should be lazy-loaded rather than removed, so the route pays the cost and the rest of the site does not. The distinction is between code the first screen needs and code that only one flow needs, and the second belongs in a lazy chunk.

// Instead of importing the whole library, import only the function used.
import debounce from 'lodash/debounce';      // small, tree-shakeable import
// not: import { debounce } from 'lodash';    // pulls the whole package

// Instead of a date library with all locales, use one with tree-shakeable
// per-function imports and load locales on demand.
import { format } from 'date-fns';            // only format is bundled

// Replace a heavy library with a platform API where one exists.
// Instead of a deep-clone library: structuredClone(value)

Tree Shaking and Side Effects

Tree shaking removes exports that are not imported, but only if the bundler can prove a module has no side effects. A package that runs code at import time or that lacks the sideEffects flag may be kept whole. Declare sideEffects false in your own package when true, and check that the dependencies you rely on are marked correctly or import their sub-paths.

{
  "name": "my-app",
  "sideEffects": ["*.css", "./src/polyfills.ts"],
  "//": "Everything else is side-effect free and can be tree-shaken."
}

Removing and Replacing Dependencies

Every dependency is code you do not control and must ship. Before adding one, check its size and whether the platform now provides the feature: fetch replaces axios for simple cases, structuredClone replaces a clone library, Intl replaces a locale library, and a few lines replace a tiny utility. Replacing a library with the platform is the most durable reduction, because the platform code is not in your bundle at all.

When you must keep a dependency, prefer a smaller alternative and check its tree-shakeability. A library that ships as one file with side effects cannot be shaken, so the whole thing stays; one with ES modules and per-function entry points can be reduced to what you use. The choice of library is a bundle-size decision as much as an API decision.

Setting a Budget

Without a budget, the bundle grows back. Set a target for the initial JavaScript, in compressed bytes, and check it in the pipeline so a pull request that adds a heavy dependency fails or is flagged. Report the size in the pull request so the reviewer sees the cost, and treat exceeding the budget as a decision rather than an accident.

Combine the budget with code splitting so the initial bundle stays small even as the app grows. The budget applies to what loads on the first screen; route and feature chunks can grow as long as they are lazy. Measure with the same tool on every build so the numbers are comparable.

Conclusion

Shrink the JavaScript bundle by analysing it to find the largest contributors, then removing, replacing with the platform, importing only the part you use, or lazy-loading the heavy ones. Enable tree shaking by declaring side effects correctly and importing sub-paths, and deduplicate across chunks. Set a budget on the initial JavaScript and check it in the pipeline so the bundle does not grow back, and report the size on each pull request so the cost is visible before the merge. The result is less code to download, parse and execute before the page is usable.

Sources: web.dev: Reduce JavaScript payloads, webpack: tree shaking, source-map-explorer.

FAQ

What are the most common sources of a large bundle?
Dependencies imported wholesale: date libraries with all locales, lodash as a whole, whole icon and component packages, and polyfills. Each looks small when added, and the total becomes the largest asset on the page, which is why analysis comes first.
How do I make tree shaking work?
Declare sideEffects correctly in your package and import sub-paths from dependencies that ship as ES modules with per-function entry points. A module the bundler cannot prove is side-effect free may be kept whole, so check the dependency is marked correctly.

Related Examples