Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Dev Server and HMR

Hot Module Replacement

Learn how Vite HMR updates modules without a page reload, how the module graph and update boundaries work, and how to use import.meta.hot accept, dispose, data and invalidate.

You save a file, and a fraction of a second later the browser shows the change, with your form input, scroll position and component state still intact. That is Hot Module Replacement (HMR). In Vite it is fast for a structural reason: when a file changes, only that module and the modules that must know about it are re-requested, and the size of your app barely matters. This lesson explains how it works and how to write HMR-aware code by hand.

Vite is not installed on this site, so the HMR calls on real Vite are read-only. The runnable examples model the update logic, which is the part worth understanding, in plain JavaScript.

The idea

  1. The dev server watches files. When one changes, it finds the module that file belongs to.
  2. It sends a message over a WebSocket to the browser: "module /src/counter.js was updated".
  3. The browser re-imports that module with a fresh timestamp (/src/counter.js?t=1718000000). Because only that URL changed, nothing else is refetched.
  4. The new module needs a way to replace the old one. This is handled by an HMR boundary: a module that has declared "I can accept updates".
  5. If no boundary is found by walking up the import chain, the server sends a full page reload.

For nearly all code you never write steps 4 and 5 yourself. Frameworks plug in through plugins: @vitejs/plugin-react uses React Fast Refresh, @vitejs/plugin-vue handles single-file components, Svelte and Solid have their own. CSS updates are always hot: Vite swaps the <style> contents.

flowchart TD
  A["You save Button.vue"] --> B["Server finds module in graph"]
  B --> C["WebSocket: update message"]
  C --> D{"Boundary found walking up importers?"}
  D -->|"yes: Button accepts itself"| E["Re-import only Button, swap in place"]
  D -->|"no boundary"| F["Full page reload"]

The module graph decides how far an update travels.

The module graph and boundaries

Vite keeps a graph of which module imports which. When util.js changes, Vite asks: does util.js accept its own update? If not, who imports it, and do they accept updates for it? It walks up the importers until it finds an accepting module (the HMR boundary) or reaches the entry.

Here is a runnable model of that walk. It is a simplified version of the algorithm, to teach the idea.

Node.js Stand-in: find the HMR boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the results: a change in util.js bubbles up to Counter.js, which is accepting, so only that boundary refreshes. A change in the entry main.js has nowhere to go, so the page reloads. Without any accepting module, everything reloads.

The import.meta.hot API

HMR code is guarded by import.meta.hot, which exists only in development. In production it is undefined, and the guarded branch is removed from the bundle.

JavaScript
// counter.js
export let count = 0;
export function increment() { count++; render(); }

function render() {
  document.querySelector('#count').textContent = count;
}

if (import.meta.hot) {
  // Accept updates for this module itself
  import.meta.hot.accept((newModule) => {
    // newModule is the fresh version (or undefined if it had a syntax error)
    newModule?.render?.();
  });

  // Run cleanup before this module is replaced
  import.meta.hot.dispose((data) => {
    data.count = count;       // keep state for the next version
  });
}

The main members:

Member Purpose
import.meta.hot.accept(cb?) Mark this module as an HMR boundary for itself; callback receives the new module
import.meta.hot.accept(dep, cb) Accept updates for a dependency (a path or an array of paths)
import.meta.hot.dispose(cb) Run cleanup (remove listeners, clear timers) before replacement
import.meta.hot.prune(cb) Run when the module is no longer imported at all
import.meta.hot.data An object that survives between versions, for carrying state
import.meta.hot.invalidate() Say "I cannot handle this update": propagates to importers or reloads
import.meta.hot.on(event, cb) Listen to events such as vite:beforeUpdate, vite:error, or custom ones from plugins
import.meta.hot.send(event, data) Send a custom event to the server

A good habit: whenever a module creates something with a lifetime (an interval, an event listener, a WebSocket), clean it up in dispose, or each edit leaves another copy running.

Preserving state: a model

This model shows the dispose/data pattern without any Vite. A "module" is replaced by a new version, and state passes through data.

Node.js Stand-in: carry state across a replacement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What frameworks do for you

  • React: Fast Refresh keeps component state when you edit a component file, as long as the file exports only components. Mixing components and non-component exports in one file can force a full re-render of that module's consumers.
  • Vue: single-file components are self-accepting; editing the template or style does not reset state, while editing <script setup> may reset that component.
  • Svelte, Solid, Preact, Lit: each plugin implements its own accept logic.
  • CSS: always hot, no state to preserve.

If HMR is broken, typical causes are circular dependencies that hide the boundary, a plugin that is not registered, or code that runs side effects at the top level without dispose.

Configuring HMR

JavaScript
export default defineConfig({
  server: {
    hmr: {
      protocol: 'ws',
      host: 'localhost',
      port: 24678,       // use another port for the HMR WebSocket
      clientPort: 443,   // port the browser should connect to (behind a proxy)
      overlay: false,    // disable the error overlay
    },
  },
});

Set server.hmr = false to disable it completely. Behind a reverse proxy or in a container, clientPort and host often need to match the externally visible address; see Proxy, CORS and HTTPS in Development.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when a changed module has no HMR boundary above it?

    If no accepting module is found while walking up the importers, Vite falls back to a full reload.
  2. 2. Which API runs cleanup code before a module is replaced?

    dispose lets the old version remove listeners and timers and store state in data.
  3. 3. Why is code wrapped in if (import.meta.hot)?

    In production, import.meta.hot is replaced so the whole branch is eliminated as dead code.
  4. 4. How does the browser learn that a module changed?

    The dev server pushes update messages over a WebSocket, and the browser re-imports the changed module.

Summary

  • HMR re-requests only the changed module and swaps it in without a page reload, so state is preserved.
  • The module graph is walked upwards to find an accepting module (the HMR boundary); no boundary means a full reload.
  • import.meta.hot provides accept, dispose, data, prune, invalidate, on and send, and only exists in development.
  • Framework plugins implement HMR for you; CSS is always hot.
  • Clean up timers and listeners in dispose to avoid duplicates after edits.

Next: Proxy, CORS and HTTPS in Development