What is HMR?
Hot Module Replacement (HMR) allows you to update modules in a running application without a full page reload. When you edit a file:- Bun detects the change
- Rebuilds only the affected modules
- Sends the update to the browser
- The browser applies the update without refreshing
- Application state (form inputs, scroll position, etc.)
- React component state
- Global variables
- WebSocket connections
Watch mode
Enable watch mode to rebuild automatically on file changes:Development server
For full HMR support, use Bun’s development server (coming soon):dev-server.ts
React Fast Refresh
React Fast Refresh is automatically enabled for.jsx and .tsx files:
Counter.tsx
- The component re-renders
- State is preserved (count value remains)
- No page reload occurs
Module types
Hot updates
Modules can opt into hot updates using theimport.meta.hot API:
Self-accepting modules
A module can handle its own updates:data.ts
Accepting dependencies
A module can handle updates to its dependencies:app.ts
CSS HMR
CSS updates are applied without a page reload:styles.css
styles.css
Image HMR
Images are also hot-reloaded:logo.png, the new image appears without a page reload.
Configuration
Debouncing
Watch mode debounces file changes to avoid rebuilding too frequently:Ignored paths
Exclude paths from watch mode:Error handling
When a build error occurs:- The error is displayed in the terminal
- The browser shows an error overlay (if using a dev server)
- The previous working code continues to run
- When you fix the error, HMR resumes
Performance
HMR in Bun is fast:- Incremental rebuilds (only changed modules)
- Parallel processing
- Minimal browser updates (only changed code)
- No disk I/O for small changes
Examples
React application
App.tsx
index.tsx
Vanilla JavaScript
app.ts
State management
store.ts
Limitations
- HMR requires a development server (static files don’t support HMR)
- Not all changes can be hot-reloaded (e.g., changing module exports)
- Some state might be lost (e.g., closures, module-level variables)
- Full page reload is needed for:
- HTML changes
- Adding/removing files
- Changes to build configuration
- Changes to imported npm packages