The Analogy: The Receiving Dock and the Palletizer
A large fulfillment warehouse handles two very different kinds of goods. The things it makes in-house sit loose on open shelves near the packing bench, because the staff touch them constantly and want to grab exactly one at a time. The things it buys from outside vendors arrive at the receiving dock, and they arrive badly organized: one vendor's order might show up as three hundred loose little cartons on a single skid, each carton wrapped and labelled in that vendor's own private scheme. Your own source files are the in-house goods; the packages in node_modules are the vendor freight.
At the receiving dock sits a palletizer. Before any vendor freight is allowed onto the pick-face, the palletizer consolidates all of one vendor's loose cartons into a single shrink-wrapped pallet, and it relabels every carton's private barcode into the one scannable format the whole warehouse uses. That is esbuild pre-bundling a dependency: hundreds of internal files are flattened into a few, and anything shipped in an old format is converted into the module format the browser can actually read. The finished pallet is parked in a staging bay, which is the node_modules/.vite cache.
The reason only vendor freight gets palletized is throughput. Pulling a finished pallet onto the floor is one forklift trip; fetching three hundred loose cartons one at a time would be three hundred trips, and the floor would jam long before the order was filled. That is exactly the difference between one request for a pre-bundled dependency and hundreds of requests for its raw internal modules. Your in-house goods stay loose on purpose: you rearrange them all day, and palletizing something you are about to open again in ten seconds would only slow you down.
The failure mode is the lot-number trap. Suppose a vendor quietly ships a corrected batch but keeps the same lot number on the paperwork. The dock scans the paperwork, sees a lot it has already palletized, and serves the old pallet straight from the staging bay. The corrected goods sit ignored. This is precisely what happens when you hand-edit files inside node_modules: the contents changed, but the lockfile and version, which is the only paperwork the palletizer reads, did not. You keep getting last week's build until you force a fresh intake and clear the staging bay.
Syntax or Core Structure
You write an ordinary bare import. On the first cold start Vite scans your source, finds that import, pre-bundles the package with esbuild into node_modules/.vite, and then rewrites the specifier to point at the cached bundle.
// what you write
import { debounce } from 'lodash-es'
// what the browser is actually served
import { debounce } from '/node_modules/.vite/deps/lodash-es.js?v=8b3f2a1c'
The ?v= query is the cache key. Because it only changes when the inputs change, pre-bundled deps are served with strong caching headers. Most projects never configure any of this, but two knobs exist for when the scan cannot see an import or a package misbehaves.
// vite.config.js
export default {
optimizeDeps: {
// force-bundle something the static scan cannot find (e.g. a dynamic import)
include: ['some-cjs-only-package'],
// leave a package unbundled (e.g. a local linked lib you edit live)
exclude: ['my-local-linked-lib'],
},
}
When a dependency genuinely changes, you clear the staging bay and re-intake with a single flag.
# rebuild the dependency cache from scratch
npx vite --force
Technical Depth: What Pre-Bundling Actually Buys
The request explosion, counted
The first problem pre-bundling solves is request count. A library published as many small ES modules costs one HTTP request per reachable internal module when served raw. The model below walks a small dependency whose entry pulls in five internal files, counts the unbundled requests, and compares that to the single request the pre-bundled pallet costs.
const dep = {
'lodash-es/index.js': ['lodash-es/map.js', 'lodash-es/filter.js', 'lodash-es/reduce.js', 'lodash-es/clone.js', 'lodash-es/merge.js'],
'lodash-es/map.js': [],
'lodash-es/filter.js': [],
'lodash-es/reduce.js': [],
'lodash-es/clone.js': [],
'lodash-es/merge.js': [],
};
function countRequests(entry) {
const seen = new Set();
(function walk(u) {
if (seen.has(u)) return;
seen.add(u);
for (const d of dep[u]) walk(d);
})(entry);
return seen.size;
}
const naive = countRequests('lodash-es/index.js');
console.log('unbundled module requests: ' + naive);
console.log('after pre-bundling: 1');
console.log('requests saved: ' + (naive - 1));
Output:
unbundled module requests: 6
after pre-bundling: 1
requests saved: 5
Six modules become one served file. Scale the internal module count from five to five hundred and the shape holds: the browser makes a single request for the pallet instead of one round trip per carton.
Convert once, reuse on warm starts
The palletizing cost is paid on a cold start and then amortized. Once a dependency is pre-bundled into node_modules/.vite, later server restarts reuse the cached result instead of re-running esbuild. The model below optimizes three packages on a cold start and then re-requests the same three on a warm restart.
const cache = new Set();
let prebuilds = 0;
function ensureOptimized(dep) {
if (cache.has(dep)) {
console.log('reuse cached pre-bundle: ' + dep);
return;
}
cache.add(dep);
prebuilds++;
console.log('pre-bundle (esbuild): ' + dep);
}
console.log('cold start:');
['react', 'react-dom', 'lodash-es'].forEach(ensureOptimized);
console.log('warm restart:');
['react', 'react-dom', 'lodash-es'].forEach(ensureOptimized);
console.log('total pre-bundles: ' + prebuilds);
Output:
cold start:
pre-bundle (esbuild): react
pre-bundle (esbuild): react-dom
pre-bundle (esbuild): lodash-es
warm restart:
reuse cached pre-bundle: react
reuse cached pre-bundle: react-dom
reuse cached pre-bundle: lodash-es
total pre-bundles: 3
Three packages, three pre-bundles total across two starts, not six. The warm restart is nearly free because the staging bay already holds the pallets.
The cache key, and why hand-edits do not bust it
The staging bay is keyed on a hash of the paperwork: the lockfile plus the dependency-relevant config. Identical paperwork yields an identical key and a cache hit; change the paperwork and the key changes, forcing a re-intake. The model below hashes the same inputs twice, then bumps the dependency version.
import { createHash } from 'node:crypto';
function key(lockfile, config) {
return createHash('sha256').update(lockfile + '\n' + config).digest('hex').slice(0, 12);
}
const lock = 'lodash-es@4.17.21';
const cfg = 'optimizeDeps.include=[]';
console.log('cache key (v1): ' + key(lock, cfg));
console.log('same inputs: ' + key(lock, cfg));
console.log('dep upgraded: ' + key('lodash-es@4.17.22', cfg));
Output:
cache key (v1): 2ec9af65639c
same inputs: 2ec9af65639c
dep upgraded: 1074f0ef3363
The first two lines match because the inputs match. The third differs because the version string changed. The trap is that hand-editing a file inside node_modules changes neither the lockfile nor the version, so the key stays 2ec9af65639c and Vite serves the stale pallet. The triggers Vite actually watches are these.
| Input | Change busts the cache? |
|---|---|
| Package manager lockfile | Yes |
| Dependency fields in package.json | Yes |
| optimizeDeps configuration | Yes |
| Resolved Vite config (relevant parts) | Yes |
| A file hand-edited inside node_modules | No |
Why esbuild here but Rollup for production
Pre-bundling is throughput work on disposable output: the pallets live in a local cache and nobody ships them. esbuild, written in Go and heavily parallel, is ideal for that because raw speed matters and output polish does not. A production bundle is the opposite: it is shipped to users, so it needs mature code-splitting, the large plugin ecosystem, and fine control over chunk boundaries. Vite makes the trade deliberately, using esbuild where the result is thrown away and Rollup where the result is the product. Pre-bundling is a dev-time convenience layer, not the production pipeline, and conflating the two leads to expecting dev pre-bundles to reflect the shape of your shipped chunks. They do not.
Real World Example: The Scanner and the Late Reload
Pre-bundling depends on a static scan of your source to know what to palletize before the browser asks. The script below models that scan: it pre-bundles the imports it can see at cold start, then a user opens a lazily loaded route whose dependency the scan never saw, and the server has to bundle it mid-session and reload.
// Vite scans source for bare imports, pre-bundles what it finds,
// then discovers anything imported dynamically only at runtime.
const staticImports = ['react', 'react-dom', 'lodash-es'];
const runtimeImports = ['chart-vendor']; // reached later via a dynamic import()
const optimized = new Set();
let reloads = 0;
function prebundle(dep) {
optimized.add(dep);
console.log('pre-bundle: ' + dep);
}
console.log('cold start scan:');
staticImports.forEach(prebundle);
console.log('user opens a lazy route:');
for (const dep of runtimeImports) {
if (!optimized.has(dep)) {
console.log('newly discovered dependency: ' + dep);
prebundle(dep);
reloads++;
console.log('full reload triggered');
}
}
console.log('optimized deps: ' + optimized.size);
console.log('mid-session reloads: ' + reloads);
Output:
cold start scan:
pre-bundle: react
pre-bundle: react-dom
pre-bundle: lodash-es
user opens a lazy route:
newly discovered dependency: chart-vendor
pre-bundle: chart-vendor
full reload triggered
optimized deps: 4
mid-session reloads: 1
At cold start the scan finds the three static imports and palletizes them. Everything is quiet until the user navigates to a route that pulls in chart-vendor through a dynamic import(). The scan never saw that specifier, so the dependency was not pre-bundled; Vite bundles it on the spot, and because a new dependency appeared after the page had already loaded, it forces a full reload. That is the "app rendered, then reloaded a second later" symptom, and the log line naming the newly optimized dependency is the tell.
The count reflects it honestly: four optimized deps but one mid-session reload that the user felt as a flicker. In a real app this compounds. Several lazy routes, each dragging in an un-scanned vendor, means several disruptive reloads scattered through the first minutes of a session, exactly when a developer is trying to work.
The fix is to declare the ones you know about up front in optimizeDeps.include, so they are palletized at cold start alongside the static imports and never trigger a late reload.
The design flaw is in the model itself, and it is instructive: the code lists runtimeImports as a known array and then "discovers" it cleanly. A real static scanner has no such list. It cannot see the target of import(someVariable) at all, because the string is only assembled at runtime. So the model is optimistic; it assumes the runtime imports are knowable, when the whole reason optimizeDeps.include exists is that they are not. The honest takeaway is that anything reached through a computed dynamic import is invisible to the scan, and the only reliable cure is to name it in config rather than hope the scanner finds it.
Common Mistakes
- Hand-editing a file inside
node_modulesand expecting the change to show up. The pre-bundle cache key does not watch file contents, so the stale pallet keeps being served. Bump the version or run--force. - Assuming a package only imported dynamically gets pre-bundled. The static scan cannot see a computed
import()target, so declare it inoptimizeDeps.includeor accept a mid-session reload. - Treating the mid-session reload as a bug in Vite. It is the scanner discovering a new dependency after load. The message names the dependency; add it to
include. - Excluding a normal package to "speed things up". Putting a many-file dependency in
excludere-creates the request explosion pre-bundling was built to prevent. - Committing
node_modules/.viteto version control. The cache is a local, machine-specific staging bay keyed on your lockfile; it should be ignored, not shared. - Expecting dev pre-bundles to match production chunks. Pre-bundling uses esbuild on disposable output; production uses Rollup. The two produce different shapes on purpose.
- Reaching for
optimizeDepsbefore diagnosing. Most projects never need it. Confirm the symptom is a scan miss or an interop failure before adding config that then has to be maintained. - Blaming interop for a "does not provide an export named" error and giving up. A CommonJS package often just needs
includeso esbuild analyzes its exports; the interop is usually fixable, not fatal. - Deleting
node_modules/.viteas a first reflex on every hiccup. It works but hides the real trigger. Understand which input changed before nuking the cache habitually.
Best Practices
- Let pre-bundling be automatic. The default scan handles almost everything; reach for config only when a concrete symptom points there.
- Declare known dynamic dependencies in
include. If you lazy-load a vendor through a computed import, name it so it is palletized at cold start instead of triggering a reload. - Ignore
node_modules/.vite. Keep the dependency cache out of version control; it is local and rebuilt from your lockfile. - Use
--forcedeliberately, not habitually. When you genuinely change a dependency out of band, clear the cache; otherwise let the key do its job. - Exclude only what must stay live. Reserve
excludefor a locally linked library you are editing, and remember it reintroduces raw request cost. - Read the reload log. A full reload just after first paint names the newly optimized dependency; treat that line as the diagnosis, not noise.
- Keep dev and production expectations separate. Verify bundle shape with an actual build; do not infer production chunks from what pre-bundling produced.
- Pin dependency versions you rely on. Because the cache key includes the lockfile, stable versions mean stable, predictable pre-bundle behavior across machines.
Practice Exercises
- Count the savings. Take the request-explosion model and change
lodash-es/index.jsto import ten internal modules instead of five. Predict the "requests saved" line before running it. - Force a cache miss. Using the cache-key model, find two different version strings that you predict will produce different keys, then confirm by running it. Explain why hand-editing a file would not change the key.
- Provoke the late reload. In a real Vite project, lazy-load a multi-file dependency through a dynamic import, start the dev server, open that route, and observe the reload. Then add the package to
optimizeDeps.includeand confirm the reload disappears. - Fix the optimistic model. Rewrite the scanner model so
runtimeImportsis not known in advance (for example, discovered from a computed string). Describe why a real static scan cannot do what your original model did, and what that implies foroptimizeDeps.include.