How do you reduce JavaScript bundle size?
IntermediatePerformance interview questionBy UIRound, updated 17 November 2026
Short answer
To reduce JavaScript bundle size, first measure what is in the bundle with an analyser, then remove the biggest items. Split code by route and load rarely used features with dynamic import(). Make sure tree shaking works, replace heavy libraries with lighter ones or native APIs, stop shipping polyfills modern browsers do not need, and serve everything compressed with Brotli or gzip.
Step 1: measure before you cut
Guessing wastes time, because one dependency is often most of the problem. Generate a treemap of the production build:
- Vite or Rollup:
rollup-plugin-visualizer. - webpack:
webpack-bundle-analyzer, orsource-map-exploreron any build with source maps. - Next.js 16:
npx next analyzefor Turbopack builds, which also shows the import chain that pulled each module in;@next/bundle-analyzerfor webpack builds.
Read three numbers for each chunk. Parsed size (minified, uncompressed) is what the engine must parse and compile. Compressed size is what crosses the network. And which chunk it is in matters most: 200 KB in a chunk loaded on one admin page is far less urgent than 50 KB in the entry chunk every visitor downloads. Then add a budget, for example with size-limit, so CI fails when the entry chunk grows. Investigate a bundle that grew from 300 KB to 900 KB walks through the whole process.
Step 2: load less up front with code splitting
Most apps ship every route in one file. Splitting by route means a visitor downloads only the page they opened. Inside a page, load heavy features when the user asks for them:
// The editor library loads only when the user clicks "Edit"
editButton.addEventListener("click", async () => {
const { createEditor } = await import("./editor.js");
createEditor(document.querySelector("#doc"));
});In React, lazy() with Suspense does the same for components; see code splitting and React.lazy. Good candidates are rich text editors, charts, maps, date pickers, modals and anything behind a tab. Splitting does not shrink the total code; it moves code off the critical path.
Step 3: make tree shaking actually work
Tree shaking removes exports nobody imports, but only if the bundler can prove they are unused. It needs ES modules (import/export), not CommonJS, and packages that declare "sideEffects": false or list their side-effectful files. Check a suspicious import in the analyser: if you import one function and the whole library appears, tree shaking failed.
import _ from "lodash"; // CommonJS: the whole library, about 70 KB minified
import { debounce } from "lodash-es"; // ES modules: just debounce and its helpersBarrel files
A barrel is an index.js that re-exports everything in a folder. Importing one name from it makes the bundler load every module it re-exports, then try to drop the unused ones. If any of those modules has side effects (a top-level import "./styles.css", a registration call), it cannot be dropped, and it ships. Barrels also slow down dev servers and tests, which must load every file. Import from the specific file in your own code, and for icon or component libraries in Next.js use optimizePackageImports, which rewrites barrel imports into direct ones.
Step 4: replace heavy dependencies
Look at the largest blocks in the treemap and ask whether you need them.
- Dates: a large date library with all locales can often become
Intl.DateTimeFormat,Intl.RelativeTimeFormator a small modular library. - Utilities:
structuredClone,Array.prototype.at,Object.groupByandfetchreplace many helper packages. - Duplicates: two versions of the same package appear as two blocks.
npm ls <package>shows why, and deduplicating or aligning versions removes one. - Server-only work: in the Next.js App Router, markdown parsing, syntax highlighting or data formatting that needs no interactivity can run in a Server Component, so its library never reaches the browser.
Check a package's size before installing it, not after.
Step 5: stop shipping code for old browsers
Transpiling to ES5 and adding polyfills for every feature can add a lot of code. Set your browser targets (a browserslist entry, or Vite's build.target) to the browsers your users actually have. Recent bundler defaults already target modern browsers. If you use core-js through Babel, the useBuiltIns: "usage" mode adds only the polyfills your code uses for those targets. See whether you still need Babel.
Step 6: minify and compress
Production builds minify by default (esbuild, Terser, SWC or Oxc). Then make sure the server or CDN sends Content-Encoding: br or gzip; JavaScript usually compresses to well under half its size. How HTTP compression works compares the options. Compression helps download time only; the browser still parses the full uncompressed code, which is why removing code matters more than compressing it.
Practise it
Start with Investigate a bundle that grew from 300 KB to 900 KB, then see why barrels and namespace imports defeat the bundler in Tree shake like webpack and Simulate tree shaking. Lazy-load route components with React.lazy and Choose gzip, Brotli, zstd or no compression cover splitting and compression.
Common follow-up questions
Why does JavaScript size matter more than image size?
An image of 100 KB is decoded off the main thread and then done. 100 KB of JavaScript must be parsed, compiled and executed on the main thread, which delays interactivity, especially on low-end phones. Byte for byte, JavaScript costs more.
Can code splitting make things slower?
Yes, if you split too finely. Each chunk is a request, and a chunk that is needed right away but loaded with import() adds a waterfall. Split at routes and at features behind an interaction, and prefetch chunks the user is likely to need next.
What is a reasonable bundle budget?
It depends on your users' devices and networks. Pick a number for the entry chunk based on what you ship today, make it fail CI when exceeded, and lower it as you remove code. A budget that is enforced matters more than the exact figure.
Does a bundler remove unused CSS too?
Not by default. CSS tree shaking depends on tooling such as CSS Modules or utility frameworks that generate only the classes you use. Unused global CSS stays unless you remove it.
Mistakes to avoid
Optimising without an analyser, by guessing which library is big
Comparing compressed sizes only and ignoring parse cost
Importing a whole library (
import * as, a CommonJS default) for one functionRe-exporting everything through barrel files that contain side effects
Lazy-loading code that every visitor needs immediately
Shipping ES5 and full polyfill sets to modern browsers
Adding a budget that nobody enforces
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Investigate a bundle that grew from 300 KB to 900 KB and enforce budgets in CIHard45 min
- Tree shake like webpack:
sideEffectsglobs, barrel re-exports, namespace imports and CommonJS bailoutsHard60 min - Simulate tree shaking: follow imports and re-exports, keep side-effectful modules and report what is removedHard50 min
- Lazy-load route components with React.lazy, preload on hover and retry failed chunksMedium40 min
- Choose gzip, Brotli, zstd or no compression by total time: transfer, decompression and parseMedium25 min