TExcelTAD
Home › Vite › Vite Dev Server & HMR

Vite Dev Server & HMR

The dev server is where you spend most of your time with Vite. It serves your files, transforms them on request, and pushes updates to the browser over a WebSocket the instant you save.

Starting the server

bash · try it yourself
npm run dev
> my-app@0.0.0 dev
> vite


  VITE v8.3.4  ready in 276 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help

"Ready in a few hundred milliseconds" is possible because nothing has been bundled yet. Work only starts when the browser asks for a file.

What happens on a request

  1. The browser loads index.html. Vite injects <script type="module" src="/@vite/client">, the HMR client.
  2. The browser sees <script type="module" src="/src/main.ts"> and requests it.
  3. Vite reads main.ts, strips the types, rewrites bare imports such as 'lodash-es' into URLs like /node_modules/.vite/deps/lodash-es.js?v=3b1c2a9f, and returns JavaScript.
  4. The browser parses those imports and requests the next files. Repeat.

Files that were already transformed are cached in memory, and dependencies get long-lived HTTP caching headers.

Dependency pre-bundling

On the first start Vite scans your source for bare imports and pre-bundles those dependencies into node_modules/.vite/deps. Two reasons:

Reason Example
CommonJS → ESM Many packages still ship CommonJS; browsers only understand ES modules
Fewer requests lodash-es has 600+ internal modules; pre-bundled it is one file

If you install a new dependency while the server runs, Vite notices and re-optimizes. Force a fresh pre-bundle with vite --force.

Hot Module Replacement (HMR)

Without HMR, saving a file would reload the whole page and lose state (form input, scroll position, an open modal). With HMR, Vite sends a message such as "/src/counter.ts changed" and the browser re-imports only that module and the modules that accept the update.

text
[vite] hmr update /src/style.css
[vite] hmr update /src/App.tsx
[vite] page reload index.html
  • CSS is always hot-swapped — Vite replaces the <style> tag.
  • Framework components (React, Vue, Svelte) are hot-swapped by the framework plugin, keeping component state.
  • Plain modules fall back to a full reload unless they (or a parent) call import.meta.hot.accept().
  • Changes to index.html or vite.config.* trigger a full reload / server restart.

The HMR API

Vite exposes import.meta.hot in development. It is undefined in production builds, so always guard it:

js
// src/counter.js
export let count = 0;
export function render(el) {
  el.textContent = `count = ${count}`;
}

if (import.meta.hot) {
  import.meta.hot.accept((newModule) => {
    // called with the freshly imported version of this file
    newModule?.render(document.querySelector('#out'));
  });
  import.meta.hot.dispose((data) => {
    data.count = count; // keep state for the next version
  });
}
API Purpose
hot.accept(cb) This module can replace itself
hot.accept('./dep.js', cb) Handle updates of a dependency
hot.dispose(cb) Clean up side effects (timers, listeners) before replacement
hot.data Object that survives between versions of the module
hot.invalidate() Give up and propagate the update to importers
hot.on(event, cb) Listen to events like vite:beforeUpdate

HMR, simulated

This playground mimics what the HMR runtime does: it keeps a registry of module versions, runs dispose on the old one, passes data along, and calls the new version — state survives the swap.

js · try it yourself
const registry = {};

function loadModule(id, factory) {
  const old = registry[id];
  const hot = { data: old ? old.hot.data : {}, disposeCb: null };
  hot.dispose = (cb) => { hot.disposeCb = cb; };
  if (old && old.hot.disposeCb) old.hot.disposeCb(hot.data);
  registry[id] = { hot, exports: factory(hot) };
  return registry[id].exports;
}

// version 1 of the "file"
let mod = loadModule('/src/counter.js', (hot) => {
  let count = hot.data.count ?? 0;
  hot.dispose((data) => { data.count = count; });
  return { inc: () => ++count, label: () => `v1 count=${count}` };
});
mod.inc(); mod.inc(); mod.inc();
console.log(mod.label());

// the developer edits the label and saves -> version 2
mod = loadModule('/src/counter.js', (hot) => {
  let count = hot.data.count ?? 0;
  hot.dispose((data) => { data.count = count; });
  return { inc: () => ++count, label: () => `v2 Count is ${count}!` };
});
console.log(mod.label());
mod.inc();
console.log(mod.label());
v1 count=3
v2 Count is 3!
v2 Count is 4!

Seeing a hot CSS update

CSS HMR is simply "replace the contents of a <style> element". Click the button to imitate saving style.css — the text in the input stays, because the page never reloads.

html · try it yourself
<!doctype html>
<html>
  <head>
    <style id="vite-style">h1 { color: #646cff; font-family: system-ui; }</style>
  </head>
  <body>
    <h1>Edit me, then "save"</h1>
    <input placeholder="type something — it survives the update" style="width: 280px">
    <button id="save">Simulate save of style.css</button>
    <script>
      const themes = [
        'h1 { color: #646cff; font-family: system-ui; }',
        'h1 { color: #e44d26; font-family: Georgia, serif; letter-spacing: 2px; }',
      ];
      let i = 0;
      document.querySelector('#save').onclick = () => {
        i = (i + 1) % themes.length;
        document.querySelector('#vite-style').textContent = themes[i];
        console.log('[vite] hmr update /src/style.css');
      };
    </script>
  </body>
</html>

Tip: If HMR seems broken, open the browser console. Vite logs [vite] connected. when the WebSocket is up and prints hmr update or page reload lines for every change.

Test yourself

What is import.meta.hot in a production build?

  1. An empty object
  2. undefined
  3. The HMR WebSocket
  4. A function

Which change always causes a full page reload rather than HMR?

  1. Editing a CSS file
  2. Editing a Vue component
  3. Editing index.html
  4. Editing a React component

What is stored in node_modules/.vite/deps?

  1. Your compiled source code
  2. Pre-bundled dependencies
  3. The production build
  4. Test snapshots