Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello, I’m Shanyue.

This is my front end engineering knowledge card collection 8/36 published in Nuggets

HMR, Hot Module Replacement, means that an old Module can be replaced without refreshing in the memory environment. This corresponds to Live Reload.

__webpack__modules__ is used to maintain all modules in the Webpack runtime. The principle of hot module replacement is to load the latest modules by chunk, find the corresponding modules in __webPack__modules__ and replace them one by one, and delete their upper and lower caches.

Its compact data structure is represented by the following code:

const __webpack_modules = [
  (module.exports, __webpack_require__) = > { __webpack_require__(0)},() = > { console.log(this is module 1)}]// JSONP asynchronously loads modules that need to be updated
self["webpackHotUpdate"] (0, {
  1: () = > {
     console.log('This is the latest module number three.')}})Copy the code

The following is a more detailed and complete process, each step involves a large number of interested can read the source code of the WebPack-Dev-server and development environment WebPack runtime.

  1. webpack-dev-serverThe packaged output bundle uses in-memory file system control instead of real file systems. In this case, it ismemfsSimulation node. Jsfs API
  2. Whenever a file is changed,webpacWill recompile,webpack-dev-serverThe file change event will be monitored and its correspondingmodule. In this case, it ischokidarMonitoring file changes
  3. webpack-dev-serverChanges to the module will be notified to the browser sidewebsocketCommunicate with the browser. In this case, it isws
  4. Browser basedwebsocketThe hash is received and a JSONP request is made to update the chunk of the module using the hash
  5. The browser loads chunk and uses the new module to hot replace the old one and remove its cache