"Webpack"--Module Hot swap

Source: Internet
Author: User

The full name is Hot module replacement (HMR), it can be understood as heat modules replacement or module hot swap, and hot plug in. NET means that the module of the program is updated during operation. This feature is primarily used in the development process and does not help the production environment (this is different from the. NET Hot swap ). The effect is the non-refresh update of the interface.

HMR-based Wds,style-loader can be used to implement a no-refresh update style. But for the JavaScript module you need to do a little extra processing, how to handle continue to look down. Since HMR is used for the development environment, we modify the configuration to make two preparations. One for production and one for development.

Const PATH = require (' path '); Const Htmlwebpackplugin= Require (' Html-webpack-plugin '); Const Webpack= Require (' Webpack '); Const PATHS={app:path.join (__dirname,' App '), Build:path.join (__dirname,' Build '),};const commonconfig={entry: {app:PATHS.app,}, Output: {path:PATHS.build, filename:' [Name].js ',}, plugins: [NewHtmlwebpackplugin ({title:' Webpack demo ',    }),  ],} function developmentconfig() {const config={devserver:{//Enable History APIHistoryapifallback:true, hotonly: true ,//close hot swap comment out this line stats:' Errors-only ', Host:process.env.Host, Port:process.env.PORT, overlay:{errors:true, Warnings:true,}}, plugins: [New Webpack.   Hotmodulereplacementplugin (), ],}; return object.assign({}, Commonconfig, config, {plugins:commonConfig.plugins.concat (config.plug INS),});} Module.exports=function(env) {Console.log ("Env", env); if(env== ' development '){    returnDevelopmentconfig (); }   returncommonconfig;};
This webpack.config.js establishes two configurations, one is Commonconfig, the other is Developmentconfig, which is distinguished by the env parameter, but how does this env parameter come about? Let's take a look at one of the previous package.json: that is, if you follow the above configuration, we start with npm start, we enter the development environment configuration, if it is a direct build, it is the way of production environment. The build method is the first section that starts Webpack directly from NPM, which does not have WDS. There is also a object.assign syntax, which merges the configuration. This time with NPM start, the console prints two logs. It seems that HRM has started. But at this point the update component.js log shows nothing is hot updated. And this 39, 36 represents the module ID, it looks very non-intuitive, here can be a plugin to make it more satisfying.
plugins: [      new  webpack. Hotmodulereplacementplugin (),       new  webpack. Namedmodulesplugin (),    ],
Start again at this time.

So the name is intuitive. But the updates we expect are still not coming out. Because you need to implement an interface
Import component from './component ', let democomponent=component ();d Ocument.body.appendChild ( DemoComponent); // HMR Interface if (module.hot) {    module.hot.accept ('./component ', () ={        const nextcomponent=  Component ();        Document.body.replaceChild (nextcomponent,democomponent);        DemoComponent=nextcomponent;    })}

and modify the Component.js:

default function () {  var element = document.createelement (' h1 ');   = ' Hello webpack ';   return element;}

This time the page has been updated. Each change page is incremented with a hot-update.js, similar to the following:

webpackhotupdate(0,{/***/"./app/component.js":/***/(function(module, __webpack_exports__, __webpack_require__) {"Use Strict"; Object.defineproperty (__webpack_exports__,"__esmodule", {value:true });/*Harmony Default Export*/__webpack_exports__["Default"] =function () {  varelement = document.createelement (' H1 '); Element.innerhtml= ' Hello web '; Element.classname= ' box '; returnelement;};/***/ })})

Update the corresponding module with Webpackhotupdate. 0 indicates the module's ID, "./app/component.js", which represents the module's name. The structure is Webpack (Id,{key:function () {}}). function take out a parenthesis, do not know what the role. The definition of webpackhotupdate is this:

 This ["webpackhotupdate"] =   function//  eslint-disable-line no-unused-vars   
Hotaddupdatechunk (Chunkid, moremodules); if (Parenthotupdatecallback) parenthotupdatecallback (Chunkid, moremodules); } ;

Summary: From the structure point of view, one is the ID, one is the corresponding modified module. But the actual implementation of the update is the Hotapply method. The whole mechanism of hot update is still a bit complicated, and the effect is like the kind of MVVM binding. Interested can be studied in depth. It is not recommended to use HMR in production, it will make the overall file larger, and no help for the generation, the next section will say the style of loading, Style-loader is the use of HMR. But for the JS module to write extra code, which makes people a bit uncomfortable.

Demo:http://files.cnblogs.com/files/stoneniqiu/webpack-ch3.zip

Reference:

https://survivejs.com/webpack/developing/configuring-hmr/https://webpack.js.org/configuration/dev-server/Series:

"Webpack"--automatic refresh and parsing

"Webpack"--Introduction and analysis

"Webpack"--Module Hot swap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.