The Analogy: The Household Move
Living in a house day to day is the development server. You take whatever you need the moment you want it: a book comes off a shelf, a wrench comes out of the garage, a coat comes off its hook, each fetched on its own the instant you reach for it. Nothing is packed, nothing is pre-sorted, and nobody has walked the whole house to decide what is worth keeping. The rooms sit fully furnished, and you pay no cost for the furniture you never touch.
The professional move is the production build, and it is a completely different operation performed on the same house. A crew arrives with the front-door inventory list, which is the entry point the browser is handed, index.html. They start there, walk only to the items the list actually names, walk on to whatever those items reference, and pack everything they reach into a small number of labeled boxes. Anything the list never points to, however useful it once seemed, is left on the curb: unreferenced modules are dead code, and Rollup drops them in the pruning we call tree-shaking.
The crew also consolidates and seals. Instead of a truck full of loose objects they make a few sealed boxes, and each box gets an inventory tag computed from the exact contents inside it, a content hash, so a box you never reopened keeps its old tag while a box whose contents changed earns a fresh one. The seasonal attic gear that most weeks nobody touches is boxed on its own and sent to off-site storage, delivered only when you specifically ask for it, exactly as a dynamically imported route is emitted as a separate chunk the browser downloads on demand rather than up front.
The trap is that the two operations obey different rules, and the house you lived in was the more forgiving of the two. At the old address a box labeled WINTER and a list line reading Winter always matched, because the old building's clerk never cared about capitalization; the new-city crew reads every label to the exact letter, fails to find Winter among the boxes, and that box never makes it onto the truck, so the room that needed it stands empty on move-in day. Nothing about your belongings changed; the move merely enforced a rule the house had always let you ignore, and that is precisely how a project that runs flawlessly in dev can arrive broken from the build.
Syntax or Core Structure
Vite runs two different engines over the same source tree, and the whole topic hangs on that fact. In development, vite prebundles dependencies with esbuild once and then serves your own modules unbundled over native ESM, transforming each file the moment the browser asks for it. In production, vite build hands the graph to Rollup, which walks it from the entry, removes dead code, splits it into chunks, minifies, and writes content-hashed files into dist/. They share config but not code paths, so a green dev server is a statement about the first engine only.
vite # dev: esbuild prebundle + native ESM, served unbundled, on demand
vite build # prod: Rollup walks the graph, tree-shakes, splits, hashes -> dist/
vite preview # serve the built dist/ locally: the closest local proxy for prod
Code splitting begins with a single syntactic distinction. A static import folds the imported module into the chunk of whoever imported it; a dynamic import() marks a boundary where Rollup starts a new chunk that is fetched only when that code actually runs. Route-level lazy loading is the highest-value use of it:
// A statically imported module folds into the importer's chunk.
import { formatDate } from './format';
// A dynamically imported module becomes its OWN chunk, fetched on demand.
const Dashboard = lazy(() => import('./routes/Dashboard'));
// ^ this import() is a code-splitting boundary
The build is shaped by a handful of options, and manualChunks is the one most often misused. It overrides Rollup's automatic grouping, which is powerful and, applied carelessly, actively harmful:
// vite.config.js - the options that shape the Rollup build
export default {
build: {
target: 'es2020', // syntax floor for the emitted code
sourcemap: true, // emit .map files so prod stack traces read
outDir: 'dist', // default output directory
chunkSizeWarningLimit: 500, // warn (kB) on large chunks: a nudge, not a fix
rollupOptions: {
output: {
// Group rarely-changing vendor code so it caches across deploys.
manualChunks: { vendor: ['react', 'react-dom'] },
},
},
},
};
The practical rule that falls out of this is simple: verify the build, never assume it. Run vite build in CI and vite preview locally, because the only way to learn what Rollup actually produces is to let Rollup run.
Technical Depth: How Rollup Decides What Ships
Three mechanisms turn a sprawling module graph into a few small files: the reachability walk that discards dead code, the entry-signature rule that assigns modules to chunks, and the manual override that can undo the second if you force it. Each is deterministic, and each can be modeled exactly in a few lines of code.
The graph walk and tree-shaking
Rollup begins at the entry and marks every module it can reach by following imports. Anything it cannot reach is dead code and never enters the bundle. The dev server does no such walk: it serves modules only when the running app asks for them, so an unreferenced or even broken-but-unreached module sits quietly in dev and simply vanishes from the build. The walk below keeps what the entry reaches and drops the rest.
// Rollup builds the production bundle by walking the module graph from the
// entry and keeping only what is reachable. Everything unreferenced is dead
// code and is dropped (tree-shaking). The dev server never does this walk.
const graph = {
'index.js': ['app.js', 'analytics.js'],
'app.js': ['router.js', 'format.js'],
'router.js': ['home.js'],
'home.js': ['format.js'],
'format.js': [],
'analytics.js': ['legacyShim.js'],
'legacyShim.js': [],
'unused.js': ['alsoUnused.js'], // nothing imports these two
'alsoUnused.js': [],
};
const reachable = new Set();
const stack = ['index.js'];
while (stack.length) {
const m = stack.pop();
if (reachable.has(m)) continue;
reachable.add(m);
for (const dep of graph[m]) stack.push(dep);
}
const all = Object.keys(graph);
const kept = all.filter((m) => reachable.has(m));
const dropped = all.filter((m) => !reachable.has(m));
console.log('entry: index.js');
console.log('kept (' + kept.length + '): ' + kept.join(', '));
console.log('dropped (' + dropped.length + '): ' + dropped.join(', '));
console.log('modules in graph: ' + all.length + ', shipped: ' + kept.length);
Output:
entry: index.js
kept (7): index.js, app.js, router.js, home.js, format.js, analytics.js, legacyShim.js
dropped (2): unused.js, alsoUnused.js
modules in graph: 9, shipped: 7
The two unused modules import each other, but nothing imports them, so the walk never reaches them and they are dropped. That is tree-shaking at module granularity; Rollup applies the same reachability logic to individual exports inside a module, so an unused named export is pruned even when the file it lives in is kept.
Splitting into chunks by entry signature
Once Rollup knows what is reachable, it decides which chunk each module belongs to. The rule is precise: a module's chunk is determined by the set of entry points that can reach it, where every dynamic import() boundary counts as an entry. Modules that share an identical signature share a chunk, so code common to two entries is hoisted into a shared chunk with no configuration at all.
| Module | Reached by | Chunk |
|---|---|---|
main.js, ui.js | main entry only | main chunk |
shared.js | main + admin | shared chunk |
admin.js, adminUi.js | admin (dynamic) | admin chunk |
// Rollup assigns each module to a chunk by its "entry signature": the set of
// entry points (the app entry plus every dynamic import() boundary) that can
// reach it. Modules with the same signature share one chunk, so code common to
// two entries is hoisted into a shared chunk automatically, with no config.
const graph = {
'main.js': ['ui.js', 'shared.js'], // static app entry
'ui.js': ['shared.js'],
'shared.js': [],
'admin.js': ['adminUi.js', 'shared.js'], // a dynamic import() boundary
'adminUi.js': [],
};
const entries = ['main.js', 'admin.js'];
function reachedBy(entry) {
const seen = new Set();
const stack = [entry];
while (stack.length) {
const m = stack.pop();
if (seen.has(m)) continue;
seen.add(m);
for (const d of graph[m]) stack.push(d);
}
return seen;
}
const sig = {};
for (const e of entries) {
for (const m of reachedBy(e)) (sig[m] = sig[m] || []).push(e);
}
const chunks = {};
for (const m of Object.keys(graph)) {
const key = sig[m].sort().join('+');
(chunks[key] = chunks[key] || []).push(m);
}
for (const [key, mods] of Object.entries(chunks)) {
console.log('chunk [' + key + ']: ' + mods.join(', '));
}
console.log('chunks: ' + Object.keys(chunks).length + ' (shared.js reached by both -> its own chunk)');
Output:
chunk [main.js]: main.js, ui.js
chunk [admin.js+main.js]: shared.js
chunk [admin.js]: admin.js, adminUi.js
chunks: 3 (shared.js reached by both -> its own chunk)
shared.js is reached by both the main entry and the dynamic admin boundary, so it lands in its own chunk that both of them load, instead of being copied into each. This automatic hoisting is exactly why hand-written chunking is so rarely worth the trouble.
manualChunks and the duplication trap
manualChunks overrides the signature rule and assigns modules to chunks by name. The failure mode is subtle: if you force a shared module into a chunk that not every one of its importers loads, Rollup cannot make those importers download a chunk they never reference, so it duplicates the module into their chunks instead. You asked for fewer files and were handed more bytes.
// Automatic chunking gives a shared module ONE home that every importer loads.
// Forcing that module into a named manualChunk which not all of its importers
// load makes Rollup COPY it into each importer's chunk instead - more bytes.
const sharedNeededBy = ['main', 'admin']; // both entries import util.js
// Automatic: Rollup puts util.js in a common chunk both entries load.
const automaticCopies = 1;
// Manual: manualChunks forces util.js into 'adminChunk'. 'main' also needs
// util.js but never loads 'adminChunk', so util.js is inlined into 'mainChunk'
// as well. Each entry that does not already load the forced home gets a copy.
const chunkThatEntryLoads = { main: 'mainChunk', admin: 'adminChunk' };
const forcedHome = 'adminChunk';
const homes = new Set();
for (const entry of sharedNeededBy) {
const loads = chunkThatEntryLoads[entry];
homes.add(loads === forcedHome ? forcedHome : loads);
}
const manualCopies = homes.size;
console.log('shared module: util.js, imported by: ' + sharedNeededBy.join(', '));
console.log('automatic chunking -> copies shipped: ' + automaticCopies);
console.log('manualChunks (forced) -> copies shipped: ' + manualCopies);
console.log(manualCopies > automaticCopies
? 'the forced split DUPLICATED a shared module: more bytes, not fewer'
: 'no duplication');
Output:
shared module: util.js, imported by: main, admin
automatic chunking -> copies shipped: 1
manualChunks (forced) -> copies shipped: 2
the forced split DUPLICATED a shared module: more bytes, not fewer
Automatic chunking shipped one copy of util.js; forcing it into a chunk only the admin entry loads shipped two. The lesson is not that manualChunks is bad, but that it should group by change-cadence, such as one stable vendor chunk, rather than slicing per dependency and fighting the hoister.
Why a passing dev server cannot vouch for the build
The asymmetry is not one bug but a family, and they share a cause: the dev server resolves and runs modules under looser rules than the build. Case-mismatched paths pass on a case-insensitive macOS or Windows disk and fail on case-sensitive Linux CI. An undeclared dependency may be found in a hoisted node_modules during dev yet be absent from a clean install. CommonJS and ESM interop can differ between esbuild's dev prebundle and Rollup's output. Import-order side effects that dev preserves can shift once chunks are reordered, and code whose only purpose is a side effect can be pruned as dead when it looks unreferenced. The defense is uniform: run the strict pipeline, vite build followed by vite preview, in the environment production uses, and treat that as the source of truth instead of the dev server.
Real World Example: The Preflight That Passed and CI That Failed
A team kept hitting the same wall: every pull request was green on the author's machine and red in CI, always on an import that could not be resolved. Rather than run the real build locally, they wrote a fast pre-push preflight that checked each imported path against the files on disk, meaning to catch the problem before it ever reached CI.
// A pre-push "preflight" a team runs to catch works-in-dev-breaks-in-CI import
// bugs. It checks that every imported path exists on disk, and is meant to fail
// locally on the same things the Linux CI build fails on.
const filesOnDisk = [
'src/App.tsx',
'src/components/Header.tsx',
'src/utils/Format.ts',
];
const importsInCode = [
'src/App.tsx',
'src/components/header.tsx', // written lowercase; the real file is Header.tsx
'src/utils/Format.ts',
];
// The shipped gate: case-insensitive match, mirroring the developer's macOS or
// Windows filesystem - the very machine where the app already runs fine.
function preflight(imports, disk) {
const have = new Set(disk.map((f) => f.toLowerCase()));
return imports.filter((imp) => !have.has(imp.toLowerCase()));
}
// What the Linux CI build actually enforces: exact, case-sensitive match.
function caseSensitive(imports, disk) {
const have = new Set(disk);
return imports.filter((imp) => !have.has(imp));
}
const gateMisses = preflight(importsInCode, filesOnDisk);
const ciMisses = caseSensitive(importsInCode, filesOnDisk);
console.log('preflight (case-insensitive) unresolved: ' + gateMisses.length);
console.log('preflight verdict: ' + (gateMisses.length === 0 ? 'PASS - safe to push' : 'FAIL'));
console.log('linux CI (case-sensitive) unresolved: ' + ciMisses.length);
ciMisses.forEach((m) => console.log(' CI cannot resolve: ' + m));
Output:
preflight (case-insensitive) unresolved: 0
preflight verdict: PASS - safe to push
linux CI (case-sensitive) unresolved: 1
CI cannot resolve: src/components/header.tsx
The output captures the whole problem in four lines. The preflight scans the imports, finds every path present on disk, and reports PASS: safe to push, so the developer pushes with confidence. Minutes later the Linux CI build fails on src/components/header.tsx, because the real file is Header.tsx and Linux matches filenames to the exact case. The gate built to prevent this exact failure waved it straight through.
The durable fix has two layers. Locally, compare against the exact on-disk names case-sensitively, independent of the host filesystem, as the caseSensitive function here already does; that alone would have surfaced the one mismatch before the push. More fundamentally, close the asymmetry by executing the strict pipeline itself: run vite build in CI on Linux as a required check, and run vite preview before shipping, because only the real build reports what the real build will do.
The design flaw is worth naming precisely, because it is not a typo but a structural mistake. The preflight lowercases both the import paths and the on-disk names before comparing them, so its match inherits the case-insensitivity of the developer's own macOS or Windows disk: the very laxness that hid the bug in the first place. It therefore validates against the same permissive rule that produced the false confidence, which makes it structurally blind to case-mismatch, the exact class of failure it was written to catch. A validator that re-implements the lax rule can only ever ratify the machine that was already wrong, and that is why an approximation of the build, however fast, can never substitute for running it.
Common Mistakes
- Trusting a green dev server as proof the build works. Dev and build run different engines; the dev server never walks the graph, tree-shakes, or splits into chunks, so it cannot surface a build-only failure. Only
vite buildexercises that path. - Never running
vite buildin CI. If the build first runs at deploy time, the first person to meet a broken build is a user. Make the build a required check on every pull request. - Skipping
vite preview. The preview server serves the actual builtdist/, the closest local stand-in for production; skip it and the first real run of your output happens in front of customers. - Case-mismatched import paths. Importing
./Headerfor a file namedheader.tsxworks on case-insensitive macOS and Windows and fails on case-sensitive Linux CI. This is the single most common works-in-dev-breaks-in-build bug. - Leaning on undeclared transitive dependencies. If you import a package you never listed in
package.json, dev may resolve it from a hoistednode_moduleswhile a clean CI install cannot, and the build fails to resolve it. - Aggressive per-dependency
manualChunks. Splitting every library into its own chunk multiplies HTTP requests, weakens compression, and creates loading waterfalls, usually making the site slower rather than faster. - Forcing a shared module into a chunk not all importers load. Rollup responds by duplicating that module into the other chunks, so a config meant to shrink the bundle quietly inflates it.
- Shipping production without sourcemaps. Minified stack traces are unreadable; with no
.mapfiles a production error points at something likeindex-9a1b.js:1:52104and nothing more. - Raising
chunkSizeWarningLimitto silence the warning. The warning is a symptom, not the disease; muting it leaves the oversized chunk in place. Investigate the bundle instead of quieting the messenger.
Best Practices
- Make
vite builda required CI gate on Linux. Build on the same operating system production uses so case-sensitivity and path resolution match; a green build there is real evidence, unlike a green dev server. - Run
vite previewbefore every release. It serves the true built output locally, catching base-path, asset, and chunk-loading problems the dev server cannot show you. - Split by route with dynamic
import()and let Rollup derive the chunks. Automatic entry-signature chunking hoists shared code correctly; reach for overrides only with evidence. - When you must use
manualChunks, group by change-cadence. A single stablevendorchunk caches well across deploys; per-package slicing fights the hoister and duplicates shared code. - Keep import paths exact-case and enforce it in tooling. A case-sensitive lint rule or preflight catches the mismatch on the developer's machine instead of in CI.
- Declare every dependency you import. List it in
package.jsonso a clean install resolves it; never rely on a transitively hoisted package being present at build time. - Ship sourcemaps for production. Set
build.sourcemapso real stack traces map back to your source, turning an opaque crash into a fixable one. - Measure the bundle before optimizing it. Generate a treemap with a visualizer plugin and look for a large dependency pulled in for one function, wholesale imports, or duplicate versions, then act on the evidence.
Practice Exercises
- Diagnose the CI-only failure. CI fails on
vite buildwith module-not-found for a file that imports fine on your machine. Give the two most likely causes and describe exactly how you would confirm which one it is. - Undo an accidental duplication. Two entries share a utility module; after you add a
manualChunksrule the total bundle grows. Explain what Rollup did and the change that restores a single shared copy. - Move a route out of the initial payload. A rarely visited admin route inflates the first download. Give the one-line code change that splits it off, and describe how the network requests differ when a user finally opens that route.
- Write the minimal build gate. Your dev server is green but the build has never run in CI. Write the minimal CI step that would catch a build-only failure and explain why it must run on Linux.