Lesson 3 of 9 · 21m
Vite's Architecture: Native ESM, Pre-Bundling, and Plugins
Vite's dev server is not a small production bundler — it is a module-serving architecture built around browser-native ESM and a separate dependency optimization pass.
The day-one fact I give new hires: in development, Vite generally does not bundle your application source. It serves modules to the browser as native ESM, transforming each requested file on demand. That inversion is why startup stays fast as app size grows: you pay for the modules a route actually imports, not the entire application upfront.
Two classes of JavaScript
Vite treats your code and dependencies differently:
src/ node_modules/
frequent edits mostly immutable
native ESM-ish mixed ESM/CJS
transform on demand pre-bundle with esbuildDependency pre-bundling exists because thousands of tiny ESM files cause a waterfall of browser requests, and because CommonJS cannot be imported as native ESM without conversion. Optimized output lands in node_modules/.vite/deps with names like react.js and chunk-ABC123.js.
The plugin pipeline is ordered
A Vite plugin can implement Rollup-style hooks (resolveId, load, transform) plus dev-server hooks (configureServer, handleHotUpdate). Ordering matters:
import react from "@vitejs/plugin-react";
export default {
plugins: [
{ name: "strip-hexscan", enforce: "pre", transform(code, id) { /* ... */ } },
react(),
],
};pre plugins run before core plugins, normal plugins in the middle, post plugins after. If your transform expects JSX to still be present and receives plain JavaScript instead, check ordering before rewriting regexes.
The import analysis rewrite
When source contains:
import { useState } from "react";the browser cannot resolve the bare specifier react. Vite rewrites it to a served URL resembling /node_modules/.vite/deps/react.js?v=123. Your authored file and the browser-served file are cousins, not twins. This is normal — but it means naive string matching in devtools can mislead you.
Field notes
- Deleting
node_modules/.viteis a valid cache reset when dependencies behave inconsistently after upgrades. optimizeDeps.includeandexcludeare levers for dependencies Vite mis-detects; use them narrowly.- Monorepos often need
optimizeDepsadjustments because linked packages are source-like but live outsidenode_modulessemantics. - A dev-only dependency error is not automatically an app bug. Inspect whether it is a pre-bundled dependency boundary problem.
Was this lesson helpful?