Sobes.tech
Middle

How does hot reload work on the example of Vue CLI?

sobes.tech AI

Answer from AI

Vue CLI uses webpack-dev-server, which includes Hot Module Replacement (HMR).

The HMR process for Vue works as follows:

  1. Starting the dev server: When you run npm run serve, webpack-dev-server starts the server and begins watching the project files.
  2. File change: When a developer saves changes to a file (.vue, .js, .css, etc.).
  3. Change detection: webpack-dev-server detects the change.
  4. Module recompile: Webpack recompiles the changed module (e.g., a Vue component).
  5. Sending update: Webpack-dev-server sends an update package (hotswap update) to the browser via WebSocket.
  6. Applying update: The HMR client-side code (built into the build) receives the package and attempts to apply it. For Vue components, this means replacing the old component definition with the new one while preserving the current state of component instances (e.g., data in data()).
  7. DOM update: Vue reactively updates the DOM using the new template or component logic without reloading the entire page.

Example of an update package structure:

{
  "hash": "...", // Build hash
  "c": { // Updated build parts
    "src/components/HelloWorld.vue": true // Module to update
  }
}

The HMR client code receives this package and runs the update logic for src/components/HelloWorld.vue.

// Pseudo-code example inside the HMR client code
if (module.hot) {
  module.hot.accept('./components/HelloWorld.vue', function() {
    // Vue component update logic that preserves state
    // Usually handled by vue-loader together with webpack-dev-server
  });
}

Thus, when a component is changed, only that component in the browser memory is updated, not the entire page, which significantly speeds up development.