How does Vite's HMR system work?
How does Vite's HMR system work?
About vitejs/vite · 2 messages · last activity 7/5/2026
Vite's HMR (Hot Module Replacement) system is a two-part architecture that handles real-time updates without full page reloads:
Client-Side HMR Handler
The client receives HMR payloads through a WebSocket connection and processes different update types in [packages/vite/src/client/client.ts:L206-L245]. The handleMessage function switches on payload types:
-
'update': Handles both JavaScript and CSS updates. For JS modules, it queues updates via
hmrClient.queueUpdate(). For CSS, it intelligently swaps stylesheet link tags to avoid Flash of Unstyled Content by cloning the old link element and removing it only after the new stylesheet loads [packages/vite/src/client/client.ts:L246-L285]. -
'full-reload': Performs a page reload when necessary (e.g., when config changes). For HTML files, it's smart—only reloading if the user is on the affected page [packages/vite/src/client/client.ts:L286-L325].
-
'custom': Allows plugins to send custom HMR events.
-
'prune': Clears specific module paths from memory.
-
'error': Displays error overlays to the developer.
Module Runner HMR
For the module runner environment, a similar handler exists in [packages/vite/src/module-runner/hmrHandler.ts:L7-L88] that handles HMR updates by:
- Unwrapping module IDs before processing
- Queueing JS updates through the hmr client
- Explicitly rejecting CSS HMR (not supported in runner mode)
- Clearing evaluated modules on full reloads and re-importing entry points
Transport & Connection
The client establishes a WebSocket connection [packages/vite/src/client/client.ts:L41-L80] with fallback logic: if the inferred HMR port fails, it retries using a direct socket target.
The HMRClient class manages the queuing and application of updates, with hooks for custom plugin logic via the hotUpdate plugin option [packages/vite/src/node/plugin.ts:L101-L140].
FOLLOW_UPS:
- How does Vite detect file changes on the server?
- What does the hotUpdate plugin hook do?
- How are circular imports handled in HMR?
Want to ask your own question?
Open chat for vitejs/vitePublic Q&A. Generated by RepoPilot from the actual source of vitejs/vite. AI answers can be incomplete or stale — verify before relying on them.