乐闻世界logo
搜索文章和话题

How does Vite's Hot Module Replacement (HMR) work?

2月19日 19:13

Vite's Hot Module Replacement (HMR) mechanism is based on browser-native ES Modules (ESM). Its working principle is as follows:

Native ESM Support: Vite leverages browser's native support for ESM to load modules directly via HTTP requests in development environments, rather than pre-bundling all modules like Webpack.

WebSocket Communication: Vite dev server establishes a WebSocket connection with the browser for real-time communication. When source code files change, the server notifies the browser through WebSocket.

Precise Module Updates: When a file is modified, Vite only recompiles that file instead of the entire application. The server sends an HMR update message containing the modified module path and update content.

Browser-side Processing: Upon receiving HMR updates, the browser accepts them through the import.meta.hot API. Vite injects HMR runtime code into each module, enabling modules to:

  • Receive new module exports
  • Execute the module's dispose function (if exists) to clean up side effects
  • Execute the module's accept function to handle updates
  • Trigger updates for other modules that depend on this module

Cascading Updates: When a module is updated, Vite automatically updates all parent modules that depend on it, ensuring the entire dependency tree remains consistent.

Difference from Webpack HMR:

  • Webpack needs to re-bundle the entire dependency graph, HMR updates require recompiling multiple modules
  • Vite only compiles modified files, HMR update speed is independent of project size
  • Webpack uses WebSocket + manifest files, Vite uses WebSocket + native ESM

Performance Advantage: Since Vite's HMR doesn't require re-bundling, even projects with thousands of modules can complete HMR updates within tens of milliseconds, providing near-instant development experience.

标签:Vite