Trung BìnhBuild Tools iconBuild Tools

HMR (Hot Module Replacement) hoạt động như thế nào?

Vite HMR nhanh hơn Webpack vì native ESM — chỉ invalidate module thay đổi thay vì recompile bundle graph; React Fast Refresh giữ component state khi edit function body, remount khi thay đổi hook order.

HMR thay thế modules trong running app mà không reload trang — giữ nguyên application state, chỉ update phần code thay đổi. Webpack HMR mechanism: Webpack watch filesystem, khi file thay đổi, compile lại module thành chunk update; dev server gửi manifest qua WebSocket cho browser; browser download update chunk; HMR runtime apply module update theo module graph — nếu module có module.hot.accept() handler, handler được gọi; nếu không, propagate lên parent modules; nếu không module nào handle, fallback toàn bộ page reload. Vite HMR: nhanh hơn nhiều vì native ESM — browser import file trực tiếp, khi file thay đổi Vite chỉ invalidate module đó và direct importers (không recompile cả bundle graph). React Fast Refresh (Vite plugin / Next.js): HMR cho React components giữ nguyên component state — edit function body, component re-render với state hiện tại (không reset state như full reload). Nếu thay đổi hooks order hay component signature → full remount. State preservation: chỉ local state được giữ; Redux/Zustand store state cũng giữ (stored outside component tree). Debugging HMR failures: nếu HMR không work, kiểm tra console — thường do circular dependencies hoặc module không có HMR handlers.

Xem toàn bộ Build Tools cùng filter theo level & chủ đề con.

Mở danh sách Build Tools