ReactMedium
Bundle size optimization?
Reduce bundle size by shipping less code to the browser: split code by route and feature, remove unused code (tree shaking, ES modules, avoiding barrel-file bloat), replace heavy dependencies with lighter ones or native APIs, move work to the server (SSR, Server Components), and measure regularly with a bundle analyzer.
Techniques
- Analyze first:
rollup-plugin-visualizer(Vite),source-map-explorer,@next/bundle-analyzerornext analyze. Find the largest modules. - Code splitting:
lazy()for routes and heavy components; dynamicimport()for rarely used libraries. - Tree shaking: use ES module builds and named imports (
import { debounce } from "lodash-es", not the wholelodash). Packages should declare"sideEffects": false. - Lighter alternatives:
date-fnsorIntlinstead ofmoment; nativefetchinstead of a client library when its features are not needed;structuredCloneinstead of deep-clone libraries. - Avoid duplicate dependencies: dedupe versions in the lockfile.
- Icons: import individual icons, not the full set.
- Polyfills: target modern browsers (Vite's default targets are modern) and avoid shipping unnecessary polyfills.
- Server Components or SSR: keep markdown parsers, date formatting and data logic on the server.
- Compression: Brotli or gzip on the server or CDN.
- Minification: done by default (Oxc in Vite 8, SWC in Next.js).
Budgets
Set size budgets in CI and fail builds that exceed them, so regressions are caught early.
Also measure the user impact
Smaller bundles improve LCP and INP, especially on mobile devices where parsing and executing JavaScript is expensive.
Code example
tsx
1// vite.config.ts - analyze and split2import { defineConfig } from "vite";3import react from "@vitejs/plugin-react";4import { visualizer } from "rollup-plugin-visualizer";56export default defineConfig({7 plugins: [react(), visualizer({ filename: "stats.html", gzipSize: true })],8});910// Before: whole libraries in the main chunk11// import _ from "lodash";12// import moment from "moment";13// import * as Icons from "lucide-react";1415// After: named imports, native APIs, lazy-loaded heavy features16import debounce from "lodash-es/debounce";17import { Search } from "lucide-react";18import { lazy } from "react";1920export const formatDate = (d: Date) => new Intl.DateTimeFormat("en-GB", { dateStyle: "medium" }).format(d);21export const onSearch = debounce((q: string) => console.log(q), 300);22export const SearchIcon = Search;23export const MarkdownEditor = lazy(() => import("./markdown-editor"));
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.