The Native ESM Dev Server

The Native ESM Dev Server in Vite: Picture a small restaurant that cooks strictly a la carte. Nothing is pre-made.

The Analogy: The A La Carte Kitchen

Picture a small restaurant that cooks strictly a la carte. Nothing is pre-made. A diner sits down, reads the menu, and points at one dish; only then does the kitchen fire that single plate. The waiter is the browser and the menu is your index.html: the browser reads the entry, sees that it asks for /src/main.js, and calls that one order back to the kitchen. The kitchen never cooks the whole menu on the chance that someone might want it.

Each plate is cooked to order and then parked on a warming shelf. The first time a dish is called, the line cook actually prepares it; every later call for the same dish is handed straight off the shelf. That warming shelf is Vite's module cache, and it is why the second request for a module is nearly free while only the first request pays the small cost of transforming it.

Contrast this with a banquet hall that lays out the entire buffet before it will open the doors. Every tray must be cooked, plated, and set out first, so opening time grows with the size of the menu whether or not anyone eats a given dish. That is the bundler-first dev server: it builds the whole graph up front, and a larger codebase simply means a longer wait before the first bite.

The failure mode is the fused plate. Imagine one dish welded to the shared table centerpiece. When the recipe for just that dish changes, the runner cannot lift it out and swap it alone; the whole table has to be cleared and re-laid. In Vite that is a lost hot-update boundary: a module that mixes a component together with other, non-swappable exports cannot be replaced in place, so instead of a surgical update the entire page reloads.


Syntax or Core Structure

A Vite project starts from a real HTML file at the project root. It is not a template that a plugin consumes; it is the entry the browser actually loads, and the script tag inside it is a genuine module request.

<!-- index.html -->
<body>
  <div id="app"></div>
  <script type="module" src="/src/main.js"></script>
</body>

The browser fetches /src/main.js, and every import inside it becomes another request that Vite answers on demand, transforming each module just in time.

// src/main.js -- the browser follows these imports one by one
import { mount } from './app.js'
import './style.css'

mount(document.getElementById('app'))

You start the server with a single command. It does not bundle first, so it is ready almost immediately and does its real work as requests arrive.

npm run dev

The mental model in one line: the browser walks the import graph, and Vite transforms-and-caches each module the moment it is asked for, never before.


Technical Depth: How the Dev Server Serves Modules

The browser builds the graph, Vite fills it

Vite does not decide up front what to transform. The browser drives it: starting from the entry, it requests a module, discovers that module's imports, and requests those in turn, walking the graph edge by edge. Vite transforms each URL the first time it is requested and remembers the result. A module on a route you never open is never requested, so it is never transformed. The small model below plays out one route open over a fixed graph.

const graph = {
  '/src/main.js':         ['/src/home.js'],
  '/src/home.js':         ['/src/ui/button.js'],
  '/src/ui/button.js':    [],
  '/src/reports.js':      ['/src/charts/heavy.js'],
  '/src/charts/heavy.js': [],
};
const cache = new Map();
function transform(url) {
  if (cache.has(url)) return;
  cache.set(url, true);
  console.log('transform ' + url);
}
function request(url) {
  transform(url);
  for (const dep of graph[url]) request(dep);
}
console.log('open route / (entry /src/main.js)');
request('/src/main.js');
console.log('modules transformed: ' + cache.size);
console.log('heavy chart transformed? ' + cache.has('/src/charts/heavy.js'));

Output:

open route / (entry /src/main.js)
transform /src/main.js
transform /src/home.js
transform /src/ui/button.js
modules transformed: 3
heavy chart transformed? false

Only the three modules reachable from the opened route were transformed. The reports page and its heavy chart sit in the graph untouched, because nothing requested them.

The cost is what you open, not what exists

On-demand serving changes the cost model. An eager bundler pays for every module in the project before serving anything; Vite pays only for the modules reachable from the route you actually open. The model below counts, over one fixed graph, how many modules each strategy would touch when you open the home route versus the admin route.

const graph = {
  '/src/main.js':    ['/src/home.js', '/src/nav.js'],
  '/src/home.js':    ['/src/ui.js'],
  '/src/nav.js':     ['/src/ui.js'],
  '/src/ui.js':      [],
  '/src/admin.js':   ['/src/table.js'],
  '/src/table.js':   ['/src/ui.js'],
  '/src/reports.js': ['/src/chart.js'],
  '/src/chart.js':   [],
};
const all = Object.keys(graph);
function reachable(entry) {
  const seen = new Set();
  (function walk(u) {
    if (seen.has(u)) return;
    seen.add(u);
    for (const d of graph[u]) walk(d);
  })(entry);
  return seen;
}
console.log('modules in project: ' + all.length);
console.log('eager (bundle all): ' + all.length);
console.log('on-demand, open /: ' + reachable('/src/main.js').size);
console.log('on-demand, open /admin: ' + reachable('/src/admin.js').size);

Output:

modules in project: 8
eager (bundle all): 8
on-demand, open /: 4
on-demand, open /admin: 3

The eager strategy always touches all eight modules; the on-demand strategy touches only the four (or three) the chosen route can reach. As a project grows, the eager number tracks the whole codebase while the on-demand number tracks a single route, which is why Vite's startup stays flat as the app gets larger.

The module cache is the warming shelf

The if (cache.has(url)) return line in the first model is the whole trick. The first request for a URL pays the transform cost; every later request for that same URL is served from memory. This is why startup is roughly constant regardless of project size: the cost is paid per module actually loaded, not per module that happens to exist in the tree. The table below contrasts the two ends of a Vite project's life.

ConcernDev serverProduction build
Module deliveryIndividual ESM requestsBundled by Rollup
Transform triggerOn demand, per requestWhole graph, ahead of time
Type checkingNot performedNot performed
Cost driverFiles you actually openWhole application

Hot updates replace only the boundary

Because Vite already holds the graph the browser built, a save does not rebuild everything. The edited module is invalidated and re-requested; unchanged modules are still cache hits. The model below loads three modules, then edits one and re-requests the same list.

const cache = new Set();
let transforms = 0;
function transform(url) {
  if (cache.has(url)) { console.log('cache hit ' + url); return; }
  cache.add(url);
  transforms++;
  console.log('transform ' + url);
}
console.log('initial load:');
['/src/main.js', '/src/home.js', '/src/ui/button.js'].forEach(transform);
console.log('edit /src/ui/button.js:');
cache.delete('/src/ui/button.js');
['/src/main.js', '/src/home.js', '/src/ui/button.js'].forEach(transform);
console.log('total transforms: ' + transforms);

Output:

initial load:
transform /src/main.js
transform /src/home.js
transform /src/ui/button.js
edit /src/ui/button.js:
cache hit /src/main.js
cache hit /src/home.js
transform /src/ui/button.js
total transforms: 4

After the edit, only button.js is transformed again; the other two are served straight off the shelf. That is the difference between a precise hot update and a full rebuild, and it is only possible because the graph is already known.

Transform is not type-check

Each module is transformed, not compiled in the strict sense: TypeScript annotations are stripped, JSX is rewritten, CSS is processed. Crucially, the types are stripped without being checked. Vite will happily serve code that tsc would reject, so a type error does not appear in the dev server at all. Run tsc --noEmit in a separate process or in CI, or a broken type will only surface later, after the code has already seemed to work in the browser.


Real World Example: A Minimal On-Demand Module Server

The dev server, stripped to its core, is a loop: given a requested module, transform it, then serve everything it imports. The script below is that loop over a small app graph, logging every transform so we can watch the request unfold. It is the same shape as the models above, but written the way the server would actually drive it from the entry.

// A minimal on-demand module server, the shape of a dev server's transform loop.
const graph = {
  '/src/main.js':   ['/src/cart.js', '/src/user.js'],
  '/src/cart.js':   ['/src/format.js'],
  '/src/user.js':   ['/src/format.js'],
  '/src/format.js': [],
};

let count = 0;
function transform(url) {
  count++;
  console.log('transform #' + count + ' ' + url);
  return { url };
}

// Serve a module: transform it, then serve everything it imports.
function serve(url) {
  transform(url);
  for (const dep of graph[url]) serve(dep);
}

console.log('browser requests entry:');
serve('/src/main.js');
console.log('total transforms: ' + count);

Output:

browser requests entry:
transform #1 /src/main.js
transform #2 /src/cart.js
transform #3 /src/format.js
transform #4 /src/user.js
transform #5 /src/format.js
total transforms: 5

The entry imports cart.js and user.js, and both of those import format.js. Following the graph depth-first, the server transforms main, then cart, then format underneath cart, then user, then format a second time underneath user. Four distinct modules, but five transforms.

That repeated format.js is the honest result of the code as written, and it points straight at the design flaw: serve has no cache. Every time a module is reached through a different importer it is transformed again. In this toy graph that is one wasted transform; in a real app where a single formatting helper is imported by fifty components, that same helper would be rebuilt fifty times on a cold load, and the cost the whole architecture is meant to avoid creeps right back in.

The fix is the warming shelf from the analogy: memoize by URL. Keep a Set (or Map) of already-transformed URLs and return early when a module has been seen, exactly as the earlier models did with cache.has(url). With that one guard, the shared format.js is transformed once and served from memory thereafter, and the transform count drops to the number of distinct modules.

This is precisely what Vite's real dev server does, which is why on-demand serving stays cheap even when the graph is densely shared. The lesson to carry out of this example is that "transform on demand" is only half the design; without the cache beside it, on demand quietly becomes on repeat.


Common Mistakes

  1. Expecting the dev server to catch type errors. Vite strips TypeScript without checking it, so code can run clean in dev and still be broken. Run tsc --noEmit as its own step.
  2. Treating index.html as a throwaway template. It is the real entry. Removing the type="module" attribute or using a path Vite cannot rewrite breaks the very first request the browser makes.
  3. Assuming production behaves like dev. Dev serves individual ES modules; production is bundled by Rollup. Code that relies on request order or on unbundled module identity can behave differently after the build.
  4. Mixing non-component exports into a component module. Exporting a constant or a side effect alongside a component often destroys the hot-update boundary, turning every save into a full page reload.
  5. Blaming Vite for a slow first paint of a huge route. The first request to a module transforms it, so a route that pulls in an enormous dependency feels that cost once. That is on-demand working as designed, not a bug.
  6. Importing Node built-ins into browser code. The browser runs your modules, and fs or path do not exist there. The dev server will not invent them for you.
  7. Writing code that depends on transform order. Because modules are transformed as they are requested, never rely on which module happened to load first for correctness.
  8. Forgetting that unopened routes are untransformed. A module with a syntax error on a route you never visit will not surface in dev until something finally requests it.
  9. Expecting the cache to notice an edit Vite never saw. Vite invalidates what it knows changed; editing a file through a tool that bypasses the watcher can leave a stale module sitting on the shelf.

Best Practices

  • Run type checking as its own step. Add tsc --noEmit to your scripts and CI so the checks the dev server skips still happen before you ship.
  • Keep index.html clean and explicit. One entry module, type="module", root-relative paths. Let Vite rewrite the URLs rather than hand-editing paths it manages.
  • Preserve hot-update boundaries. Keep component modules focused so a save can swap one module in place instead of forcing the whole page to reload.
  • Import only what a module needs. On-demand transform rewards small, focused modules; a fat barrel file drags its whole surface into the first request that touches it.
  • Test the production build regularly. Run the build and preview it, because dev and build differ, and you do not want to discover bundling problems at release time.
  • Let the browser drive the graph. Reach for import and let Vite resolve and transform on demand instead of manually concatenating files.
  • Keep browser and server code apart. Do not pull Node-only modules into code the browser loads; isolate platform-specific code behind clear boundaries.
  • Trust the cache, but know how to bust it. Understand that the shelf holds transformed modules, and restart or clear it when an out-of-band change leaves something stale.

Practice Exercises

  1. Predict the transforms. Using the first model's graph, open the /reports route instead of / by requesting /src/reports.js, and predict exactly which modules are transformed before you run it.
  2. Fix the double transform. Take the Real World Example and add a URL cache to serve so format.js is transformed once. Confirm the total transform count drops to four.
  3. Break a hot boundary on purpose. In a real Vite app, export a plain object from the same module as a component, edit it, and observe whether the update is surgical or a full reload. Explain what you see.
  4. Prove types are not checked. Add a deliberate type error to a module, load it in the dev server, then run tsc --noEmit. Describe where the error shows up and where it does not.