Skip to main content

Frontend development · Intermediate · 24 min

Find what makes your JavaScript bundle big and shrink it

By Padding · Updated 18 Nov 2026
Node.js 26 · Vite 8.3.8 · rollup-plugin-visualizer 7.1.3 · size-limit 14.3.0 · checked in the node:26 image

You will take a Vite page from about 530 kB of JavaScript to under 7 kB by finding the heavy modules with rollup-plugin-visualizer, importing only the icons you use, swapping a date library for Intl and lazy-loading a rarely used screen, then guard the result with a size-limit budget that fails the build.

On this page

Most oversized JavaScript bundles are not caused by your own code. They come from one or two imports that pull in far more than the page uses: a whole date library to format three dates, a whole icon set to draw three icons, or a settings screen that hardly anyone opens but everyone downloads. Each of these costs data on a prepaid plan, and the browser has to parse and run all of it before the page responds, which is slowest on the low-end Android phones many people use.

In this tutorial you build a small page for Riverside Market, a fictional weekly street market, the way many projects start: with moment for dates and lucide icons registered all at once. You measure it, find the two heavy modules, fix each one, lazy-load a rarely used report, prove the page still works in a real browser, and finish with a size budget that stops the build when the main chunk grows again.

Everything runs in a throwaway folder, ~/bundle-diet-demo, which the last step removes.

Step 1 · Build the page the way it often starts

Create the project, mark it as an ES module package (Vite loads vite.config.js as ESM, and rollup-plugin-visualizer 7 can only be loaded that way), and install pinned versions of Vite and the two runtime libraries:

Bash
mkdir -p ~/bundle-diet-demo/src
cd ~/bundle-diet-demo
npm init -y > /dev/null
npm pkg set type=module
npm pkg set scripts.build="vite build"
npm install --save-dev vite@8.3.8
npm install moment@2.31.0 lucide@1.76.0

Write the page. It lists the next three market days with an icon each, and has a button that shows a report for stall holders:

Bash
cd ~/bundle-diet-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Riverside Market</title>
</head>
<body>
  <main>
    <h1>Riverside Market</h1>
    <p>Next market days</p>
    <ul id="days"></ul>
    <button id="open-report" type="button">Stall holder report</button>
    <section id="report"></section>
  </main>
  <script type="module" src="/src/main.js"></script>
</body>
</html>
HTML

cat > src/report.js <<'JS'
const stalls = [
  { section: 'Fruit and veg', count: 14 },
  { section: 'Fabrics', count: 9 },
  { section: 'Phones and repairs', count: 6 },
  { section: 'Cooked food', count: 11 },
];

export function renderReport(target) {
  const total = stalls.reduce((sum, s) => sum + s.count, 0);
  const rows = stalls
    .map((s) => `<tr><th scope="row">${s.section}</th><td>${s.count}</td></tr>`)
    .join('');
  target.innerHTML = `
    <h2>Stall holder report</h2>
    <table>
      <thead><tr><th scope="col">Section</th><th scope="col">Stalls</th></tr></thead>
      <tbody>${rows}</tbody>
      <tfoot><tr><th scope="row">Total</th><td>${total}</td></tr></tfoot>
    </table>`;
}
JS

cat > src/main.js <<'JS'
import moment from 'moment';
import { createIcons, icons } from 'lucide';
import { renderReport } from './report.js';

const marketDays = [
  { start: '2026-11-21T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-11-28T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-12-05T07:00', place: 'Old bus depot', icon: 'map-pin' },
];

const list = document.querySelector('#days');
list.innerHTML = marketDays
  .map((day) => {
    const when = moment(day.start);
    return `<li>
      <i data-lucide="calendar" aria-hidden="true"></i>
      <time datetime="${day.start}">${when.format('dddd D MMMM')}</time>
      from ${when.format('HH:mm')}
      <i data-lucide="${day.icon}" aria-hidden="true"></i> ${day.place}
    </li>`;
  })
  .join('');

createIcons({ icons });

document.querySelector('#open-report').addEventListener('click', () => {
  renderReport(document.querySelector('#report'));
});
JS

npm run build

Nothing here looks unusual. createIcons({ icons }) is a copy-paste line from many examples, and moment has been the default date library in countless projects.

Check it worked

The build ends with a table of output files. The JavaScript line reads something like dist/assets/index-<hash>.js 530.43 kB │ gzip: 127.10 kB, and Vite adds a warning that some chunks are larger than 500 kB after minification. That is half a megabyte of script for a list of three dates.

Step 2 · See what is inside and what it costs

The Vite size table tells you the total, not the cause. rollup-plugin-visualizer records every module that went into each chunk and how big it is. Vite 8 runs Rollup-compatible plugins, so it works as a Vite plugin. Install it and add it to a Vite config, asking for two reports: an interactive treemap to open in a browser, and a Markdown summary you can read in the terminal.

Bash
cd ~/bundle-diet-demo
npm install --save-dev rollup-plugin-visualizer@7.1.3
cat > vite.config.js <<'JS'
import { defineConfig } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  plugins: [
    visualizer({ filename: 'stats.html', gzipSize: true, brotliSize: true }),
    visualizer({ filename: 'stats.md', template: 'markdown', gzipSize: true, brotliSize: true }),
  ],
});
JS
npm run build > /dev/null
sed -n '/## Top 10/,/^$/p' stats.md

Open stats.html in your browser (open stats.html on macOS, xdg-open stats.html on Linux). Green rectangles are dependencies from node_modules, blue ones are your own files, and the area of each rectangle is its size. Hover a rectangle to see its rendered, gzip and brotli sizes.

The report's sizes describe modules. What the phone downloads is the chunk file, compressed by your server. Write a small script that measures each built file three ways: raw (what the browser has to parse), gzip, and brotli (the two encodings servers commonly send):

Bash
cd ~/bundle-diet-demo
cat > sizes.mjs <<'JS'
import { readdirSync, readFileSync } from 'node:fs';
import { gzipSync, brotliCompressSync, constants } from 'node:zlib';

const kb = (n) => `${(n / 1000).toFixed(2)} kB`.padStart(10);
for (const name of readdirSync('dist/assets').filter((f) => f.endsWith('.js'))) {
  const raw = readFileSync(`dist/assets/${name}`);
  const gzip = gzipSync(raw, { level: 9 }).length;
  const brotli = brotliCompressSync(raw, {
    params: { [constants.BROTLI_PARAM_QUALITY]: 11 },
  }).length;
  console.log(`${name.padEnd(22)} raw ${kb(raw.length)}  gzip ${kb(gzip)}  brotli ${kb(brotli)}`);
}
JS
node sizes.mjs

Two things to take from these numbers. First, the compressed size is what costs data, but the raw size is what costs CPU time: a 530 kB script is parsed and compiled in full even though it arrives as about a quarter of that. Second, the visualizer compresses each module on its own, so its gzip and brotli totals at the top of stats.md add up to far more than the real file. Use the visualizer to compare modules with each other, and sizes.mjs (or Vite's gzip column) for what actually ships.

Check it worked

The Top 10 list starts with /node_modules/moment/dist/moment.js (about 114 KiB rendered) and /node_modules/lucide/dist/esm/iconsAndAliases.mjs (about 78 KiB), followed by hundreds of small lucide/dist/esm/icons/... files for icons such as hop and wheat-off that the page never shows. In stats.html the green areas fill almost the whole treemap and src/main.js is a sliver. sizes.mjs prints one index- file of about 530 kB raw, roughly 124 kB gzip and 103 kB brotli. Its gzip figure is a little below Vite's because the script uses the highest compression level.

Step 3 · Import only the icons you use

createIcons({ icons }) passes Lucide's full catalogue of icons to the function, so the bundler has to keep every one of them: it cannot know which names your HTML will ask for at run time. Lucide's own guide warns that this bundles all icons. The fix is to import the three icons by name and pass only those. Because Lucide ships ES modules marked as free of side effects, the bundler can then drop every icon you did not name. This is tree shaking: unused exports are removed because nothing imports them.

Replace src/main.js. Only the import line and the createIcons call change:

Bash
cd ~/bundle-diet-demo
cat > src/main.js <<'JS'
import moment from 'moment';
import { createIcons, Calendar, MapPin, Store } from 'lucide';
import { renderReport } from './report.js';

const marketDays = [
  { start: '2026-11-21T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-11-28T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-12-05T07:00', place: 'Old bus depot', icon: 'map-pin' },
];

const list = document.querySelector('#days');
list.innerHTML = marketDays
  .map((day) => {
    const when = moment(day.start);
    return `<li>
      <i data-lucide="calendar" aria-hidden="true"></i>
      <time datetime="${day.start}">${when.format('dddd D MMMM')}</time>
      from ${when.format('HH:mm')}
      <i data-lucide="${day.icon}" aria-hidden="true"></i> ${day.place}
    </li>`;
  })
  .join('');

createIcons({ icons: { Calendar, MapPin, Store } });

document.querySelector('#open-report').addEventListener('click', () => {
  renderReport(document.querySelector('#report'));
});
JS
npm run build > /dev/null
node sizes.mjs

The same pattern applies to most libraries that offer many small pieces: import { debounce } from 'lodash-es' rather than import _ from 'lodash', or one chart type rather than the whole charting package. A namespace import (import * as x) or an object of everything, used with names chosen at run time, keeps the lot.

If a new icon later shows up as an empty space, it is because its name is in the HTML but not in the import. Add it to both.

Check it worked

sizes.mjs now shows the index- file at roughly 68 kB raw and about 23 kB gzip, down from 530 kB. Look at stats.md again: iconsAndAliases.mjs and the long tail of unused icon files are gone, and moment.js is now the largest module by far.

Step 4 · Format dates with Intl instead of a library

The page uses moment to print a weekday, a date and a time. Every current browser can already do that through Intl.DateTimeFormat, using locale data that ships with the browser, so it adds nothing to your bundle. Moment's own documentation describes the project as in maintenance mode and points to Intl and smaller libraries for new work.

Create the formatters once and reuse them. Passing undefined as the locale uses the reader's browser language, so the same code prints English for one visitor and Swahili or French for another:

Bash
cd ~/bundle-diet-demo
cat > src/main.js <<'JS'
import { createIcons, Calendar, MapPin, Store } from 'lucide';
import { renderReport } from './report.js';

const marketDays = [
  { start: '2026-11-21T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-11-28T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-12-05T07:00', place: 'Old bus depot', icon: 'map-pin' },
];

const dayFormat = new Intl.DateTimeFormat(undefined, {
  weekday: 'long',
  day: 'numeric',
  month: 'long',
});
const timeFormat = new Intl.DateTimeFormat(undefined, {
  hour: '2-digit',
  minute: '2-digit',
  hourCycle: 'h23',
});

const list = document.querySelector('#days');
list.innerHTML = marketDays
  .map((day) => {
    const when = new Date(day.start);
    return `<li>
      <i data-lucide="calendar" aria-hidden="true"></i>
      <time datetime="${day.start}">${dayFormat.format(when)}</time>
      from ${timeFormat.format(when)}
      <i data-lucide="${day.icon}" aria-hidden="true"></i> ${day.place}
    </li>`;
  })
  .join('');

createIcons({ icons: { Calendar, MapPin, Store } });

document.querySelector('#open-report').addEventListener('click', () => {
  renderReport(document.querySelector('#report'));
});
JS
npm uninstall moment
npm run build > /dev/null
node sizes.mjs

new Date('2026-11-21T07:00') reads a date and time without a time zone as local time, which is what moment('2026-11-21T07:00') did too, so the output does not shift. hourCycle: 'h23' keeps a 24-hour clock in every locale, matching the HH:mm format the page used before.

A note for multilingual audiences: browsers do not carry full data for every language. In the Chromium build that Playwright downloads, sw-KE gives Jumamosi, 21 Novemba and fr-SN gives samedi 21 novembre, but Hausa (ha-NG) and Yoruba (yo-NG) fell back to a bare format, something like M11 21, Sat. Test the languages your readers actually use, in the browsers they actually use, before you rely on them.

Check it worked

sizes.mjs shows the index- file at roughly 5.3 kB raw and about 2.5 kB gzip. npm ls moment prints an empty tree, and stats.md no longer mentions moment.

Step 5 · Load the report only when someone asks for it

The stall holder report is used by a handful of people once a week, yet its code is in the main chunk that every shopper downloads. A dynamic import() call tells Vite to put that module in its own chunk and fetch it only when the call runs. import() returns a promise for the module, so the click handler becomes async.

Replace the import of report.js at the top and the click handler at the bottom of src/main.js:

Bash
cd ~/bundle-diet-demo
cat > src/main.js <<'JS'
import { createIcons, Calendar, MapPin, Store } from 'lucide';

const marketDays = [
  { start: '2026-11-21T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-11-28T07:00', place: 'Riverside car park', icon: 'store' },
  { start: '2026-12-05T07:00', place: 'Old bus depot', icon: 'map-pin' },
];

const dayFormat = new Intl.DateTimeFormat(undefined, {
  weekday: 'long',
  day: 'numeric',
  month: 'long',
});
const timeFormat = new Intl.DateTimeFormat(undefined, {
  hour: '2-digit',
  minute: '2-digit',
  hourCycle: 'h23',
});

const list = document.querySelector('#days');
list.innerHTML = marketDays
  .map((day) => {
    const when = new Date(day.start);
    return `<li>
      <i data-lucide="calendar" aria-hidden="true"></i>
      <time datetime="${day.start}">${dayFormat.format(when)}</time>
      from ${timeFormat.format(when)}
      <i data-lucide="${day.icon}" aria-hidden="true"></i> ${day.place}
    </li>`;
  })
  .join('');

createIcons({ icons: { Calendar, MapPin, Store } });

document.querySelector('#open-report').addEventListener('click', async () => {
  const { renderReport } = await import('./report.js');
  renderReport(document.querySelector('#report'));
});
JS
npm run build

The report here is tiny, so this split does not pay for itself: to load a chunk on demand, Vite adds a small preload helper (about 1 kB) to the main chunk, which is more than the report weighs. The pattern is what matters, and it pays off as soon as the split-out code is bigger than a few kilobytes. Real candidates are an admin screen, a rich text editor, a map, a chart library or a PDF exporter: large, and needed by few visits. Keep anything the first screen needs in the main chunk; splitting it out only adds a second round trip before the page can render.

On a slow connection the gap between the click and the report can be noticeable. For a real feature, show a short loading message in the handler and catch a failed import() (for example when the phone goes offline) so the button does not silently do nothing.

Check it worked

The build output now lists two JavaScript files: dist/assets/report-<hash>.js of about half a kilobyte, and the index- file, now about 6.5 kB raw and 3 kB gzip, a little larger than before because of the preload helper. Open stats.html and you see two top-level rectangles, one per chunk.

Step 6 · Check the slimmer page still works in a browser

Every change so far altered how code is loaded, which is where size work usually breaks things: a missing icon, a date in the wrong format, a lazy chunk that never loads. Check the built files in a real browser. Install Playwright and Chromium (--with-deps also installs the system libraries Chromium needs on Linux and can ask for your password):

Bash
cd ~/bundle-diet-demo
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromium

The test hands the files in dist/ straight to the browser, so no server needs to run. It loads the page in English (UK) and in Swahili (Kenya), checks the dates and icons, and confirms the report chunk is only requested after the click:

Bash
cd ~/bundle-diet-demo
cat > check-page.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';

// Serve dist/ to the browser without running a web server.
const dist = fileURLToPath(new URL('./dist/', import.meta.url));
const origin = 'http://market.localhost';

async function openPage(browser, locale) {
  const context = await browser.newContext({ locale });
  const requested = [];
  await context.route(`${origin}/**`, (route) => {
    const path = new URL(route.request().url()).pathname;
    requested.push(path);
    route.fulfill({ path: dist + (path === '/' ? 'index.html' : path.slice(1)) });
  });
  const page = await context.newPage();
  await page.goto(`${origin}/`);
  return { page, requested };
}

const browser = await chromium.launch();

// English (UK): dates come from Intl, and the three icons per row are drawn.
const { page, requested } = await openPage(browser, 'en-GB');
const items = page.locator('#days li');
assert.equal(await items.count(), 3);
assert.match(await items.first().innerText(), /Saturday 21 November\s+from 07:00/);
assert.equal(await page.locator('#days svg').count(), 6, 'six icons drawn');

// The report chunk is not downloaded until someone asks for it.
assert.ok(!requested.some((p) => p.includes('/assets/report-')), 'report not loaded at start');
await page.getByRole('button', { name: 'Stall holder report' }).click();
await page.getByRole('table').waitFor();
assert.ok(requested.some((p) => p.includes('/assets/report-')), 'report loaded on click');
assert.match(await page.getByRole('table').innerText(), /Total\s+40/);

// Swahili (Kenya): same code, the browser's own locale data.
const sw = await openPage(browser, 'sw-KE');
assert.match(await sw.page.locator('#days li').first().innerText(), /Jumamosi/);

await browser.close();
console.log('PASS: dates, icons and the lazy report all work');
JS
node check-page.mjs

To look at the page yourself, run npx vite preview and open the address it prints (port 4173 by default). Press Ctrl+C to stop it.

Check it worked

The last line of output is PASS: dates, icons and the lazy report all work. To see the test catch a real regression, change { Calendar, MapPin, Store } to { Calendar, Store } in src/main.js, run npm run build and node check-page.mjs again: it fails with six icons drawn, because the Old bus depot row loses its map pin. Put MapPin back and rebuild.

Step 7 · Set a size budget that fails the build

The page is now about 2.6 kB of brotli-compressed JavaScript. Without a guard, the next convenient import puts it back where it started. size-limit checks built files against a limit and exits with an error when they are over it, which stops npm run build locally and in CI.

Install it with its file plugin, which measures files you have already built (brotli by default, the encoding most browsers accept). Then give the main chunk a limit with some headroom, and run the check after every build:

Bash
cd ~/bundle-diet-demo
npm install --save-dev size-limit@14.3.0 @size-limit/file@14.3.0
cat > .size-limit.json <<'JSON'
[
  {
    "name": "main chunk",
    "path": "dist/assets/index-*.js",
    "limit": "4 kB"
  }
]
JSON
npm pkg set scripts.build="vite build && size-limit"
npm run build

The path is a glob because the file name contains a content hash that changes on every edit. Vite empties dist/ before each build, so the glob always matches exactly one file. Pick a limit a little above today's size rather than a round number far away; a budget only helps if a mistake pushes you over it. Add "gzip": true to the entry if your server sends gzip and not brotli.

Check it worked

After the Vite output, size-limit prints a block with Size limit: 4 kB and Size: followed by about 2.6 kB brotlied, and the command exits normally. echo $? straight after prints 0.

Step 8 · Check a dependency before you add it

Say the market wants labels such as "in 2 days" and someone suggests dayjs with its relative time plugin. Before installing anything, look the package up on a bundle size site such as bundlephobia.com (https://bundlephobia.com/package/dayjs@1.11.23), which reports its minified and gzipped size, about 7 kB and 3 kB at the time of writing. Those figures are for the package alone and do not include plugins, so the honest test is your own build. Try it, keeping a copy of main.js to go back to:

Bash
cd ~/bundle-diet-demo
npm install dayjs@1.11.23
cp src/main.js src/main.js.bak
cat >> src/main.js <<'JS'

// Trial: "in 2 days" labels with dayjs
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime.js';
dayjs.extend(relativeTime);
console.log(dayjs(marketDays[0].start).fromNow());
JS
npm run build || echo "The size budget stopped the build"

The budget caught it. For this page the free option is Intl.RelativeTimeFormat, which is built into the browser like Intl.DateTimeFormat and turns a number of days into text such as "in 2 days" in the reader's language. Put the original file back and remove the trial package:

Bash
cd ~/bundle-diet-demo
mv src/main.js.bak src/main.js
npm uninstall dayjs
npm run build

Sometimes the library is worth it. Then raise the limit in .size-limit.json on purpose, in the same commit, so the increase is a decision someone reviewed rather than a drift nobody noticed.

Check it worked

The trial build prints Package size limit has exceeded by followed by about 2 kB, then Size: 6.08 kB brotlied or close to it, and your echo line The size budget stopped the build. After the revert, npm run build passes again with the main chunk back at about 2.6 kB.

Step 9 · Clean up

Remove the demo folder, which also removes the local Playwright package. The Chromium that Playwright downloaded stays in its shared cache; npx playwright uninstall removes it if you no longer need it.

Bash
cd ~
rm -rf ~/bundle-diet-demo

Check it worked

ls ~/bundle-diet-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.