Skip to content
Performance & Accessibility

Tree Shaking and Bundle Size, Done Properly

Removing unused code from JavaScript bundles during the build, so visitors only download the functions a page actually uses.

MediaScaleUp Editorial Team 2 min read 12 views
Tree Shaking and Bundle Size, Done Properly

At a glance

  • Tree shaking dead-code elimination based on static ES module imports and exports
  • Requirement code written as ES modules with side-effect-free imports
  • Coverage tab Chrome DevTools shows how much loaded code is unused
  • Cost of JavaScript download, parse, compile and execute time on the device

Why it matters

Why it matters: JavaScript is the most expensive resource per byte because it must be downloaded, parsed and executed, and unused library code is common in modern bundles.

Best practice

  • Import only the functions you use
  • Analyze bundles with a bundle visualizer
  • Mark packages as side-effect free where accurate
  • Replace heavy libraries with smaller alternatives
  • Set a JavaScript budget per page type
What to do and what to avoid with tree shaking and bundle size, side by side
Good practice against the usual mistakes, from the sources listed below.

Common pitfalls

Watch out for:

  • Importing whole utility libraries for one function
  • CommonJS dependencies that block tree shaking
  • Shipping polyfills to browsers that do not need them
  • Ignoring bundle growth between releases

When to call in a specialist

Bottom line Bring in help when JavaScript bundles are large, when builds have grown over time, or when mobile performance lags.

Where this comes from

The figures and practices above come from the sources listed.

Working on something like this?

We take on Performance & Accessibility work for teams who want it done once, properly. Tell us what you are building and we will tell you honestly whether we are the right studio for it. Start a project.

Where to go next

Spotted something wrong? Report an error on this page. We correct on the page and say what changed.

All services

The work behind this article, and what it costs.

MediaScaleUp Editorial Team

Articles here are researched, written and checked by the MediaScaleUp studio team before they are published, and dated when they are reviewed.

Keep reading

More in Performance & Accessibility