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.
webpack-dev-server
The packaged output bundle uses in-memory file system control instead of real file systems. In this case, it ismemfsSimulation node. Jsfs
API- Whenever a file is changed,
webpac
Will recompile,webpack-dev-server
The file change event will be monitored and its correspondingmodule
. In this case, it ischokidarMonitoring file changes webpack-dev-server
Changes to the module will be notified to the browser sidewebsocket
Communicate with the browser. In this case, it isws- Browser based
websocket
The hash is received and a JSONP request is made to update the chunk of the module using the hash - The browser loads chunk and uses the new module to hot replace the old one and remove its cache