How does Vite's HMR system work?
How does Vite's HMR system work?
About vitejs/vite · 2 messages · last activity 7/19/2026
Vite's HMR (Hot Module Replacement) system is a multi-layered architecture that enables fast updates during development. Here's how it works:
Core HMR Flow
Client-Side Message Handling
The client receives HMR payloads through a WebSocket connection and processes them in [packages/vite/src/client/client.ts:L206-L245]. When an update payload arrives, the system:
- Notifies listeners of
vite:beforeUpdate - Checks if there's an error overlay (which requires a full reload if it's the first update)
- Processes each update—either a JS update or CSS update
JS Updates vs CSS Updates
JS Updates: Queued through hmrClient.queueUpdate() for module-level updates [packages/vite/src/client/client.ts:L225].
CSS Updates: For CSS files referenced with <link> tags, the system [packages/vite/src/client/client.ts:L230-L245]:
- Finds the corresponding
<link>element in the DOM - Updates its href with a new timestamp to force the browser to fetch the latest version
Module Runner Support
For environments using the module runner (like SSR), [packages/vite/src/module-runner/hmrHandler.ts:L7-L88] provides a specialized HMR handler that:
- Handles JS updates by unwrapping module IDs and queuing them
- Rejects CSS HMR (not supported in runner mode)
- Supports full-reload with entrypoint tracking via [packages/vite/src/module-runner/hmrHandler.ts:L97-L120]
- Handles custom events, pruning, and error notifications
HMR Plugin Hook
Plugins can intercept HMR updates via the handleHotUpdate hook [packages/vite/src/node/plugin.ts:L341-L380], which allows custom logic to determine affected modules or send custom payloads.
WebSocket 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 tries a direct socket host to ensure connectivity even in complex network setups.
FOLLOW_UPS:
- What types of HMR payload messages does Vite support?
- How does CSS module injection work during HMR updates?
- Can plugins customize HMR behavior for specific file types?
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.