Home > Web Front-end > JS Tutorial > Webpack hot module replacement (HMR)/hot update method

Webpack hot module replacement (HMR)/hot update method

亚连
Release: 2018-05-26 14:56:31
Original
2359 people have browsed it

The function of module hot module replacement (HMR) is to replace, add, and delete necessary modules without refreshing the page when the application is running. This article mainly introduces the webpack hot module replacement (HMR)/hot update. The method is now shared with everyone, and also serves as a reference for everyone.

This is an article about the simplest configuration of webpack hot module replacement (react is not required), also called hot update.

The function of hot module replacement (HMR) is to replace, add, and delete necessary modules without refreshing the page when the application is running. HMR is useful for applications that consist of a single state tree. Because the components of these applications are "dumb" (as opposed to "smart"), after the component's code changes, the state of the component can still correctly reflect the latest state of the application.

webpack-dev-server has built-in "live reload", which will automatically refresh the page.

The file directory is as follows:

  1. app

    1. ##a.js

    2. component.js

    3. index.js

  2. node_modules

  3. package.json

  4. webpack.config.js

  5. ##a.js is imported into component.js. index.js imports component.js. Modifying any file can achieve the hot update function.

The most important thing is that in index.js, there is such a piece of code: (Must be required to complete hot update)

if(module.hot){
  module.hot.accept(moduleId, callback);
}
Copy after login

The following is package.json configuration:

{
 "name": "webpack-hmr",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
  "start": "nodemon --watch webpack.config.js --exec \"webpack-dev-server --env development\"",
  "build": "webpack --env production"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "devDependencies": {
  "html-webpack-plugin": "^2.28.0",
  "nodemon": "^1.11.0",
  "webpack": "^2.2.1",
  "webpack-dev-server": "^2.4.1"
 }
}
Copy after login

As you can see from the dependencies, this is really the simplest configuration. Among them, nodemon is used to monitor the status of the webpack.config.js file. As long as there is a change, the command will be re-executed.

Regarding "html-webpack-plugin", it can be omitted here. For specific configuration, please see: https://www.npmjs.com/package/html-webpack-plugin.

Here, two commands are defined, one is start, used in the development environment; the other is build, used in the production environment. --watch is used to monitor one or more files, and --exec is used by nodemon to execute other commands. For specific configuration, please see: https://c9.io/remy/nodemon.

The next step is webpack.config.js. Since two commands are defined in the scripts of package.json, we still have to implement two situations (development and production) in the configuration file. You can also modify the configuration. one of them).

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 + '/index.js',
 },
 output: {
  path: PATHS.build,
  filename: '[name].js',
 },
 watch: true,
 plugins: [
  new HtmlWebpackPlugin({
   title: 'Webpack demo',
  }),
 ],
}

function developmentConfig(){
 const config ={
  devServer:{
   historyApiFallback:true, //404s fallback to ./index.html
   // hotOnly:true, 使用hotOnly和hot都可以
   hot: true,
   stats:'errors-only', //只在发生错误时输出
   // host:process.env.Host, 这里是undefined,参考的别人文章有这个
   // port:process.env.PORT, 这里是undefined,参考的别人文章有这个
   overlay:{ //当有编译错误或者警告的时候显示一个全屏overlay
    errors:true,
    warnings:true,
   }
  },
   plugins: [
   new webpack.HotModuleReplacementPlugin(),
   new webpack.NamedModulesPlugin(), // 更新组件时在控制台输出组件的路径而不是数字ID,用在开发模式
   // new webpack.HashedModuleIdsPlugin(), // 用在生产模式
  ],
 };
 return Object.assign( 
  {},
  commonConfig,
  config,
  {
   plugins: commonConfig.plugins.concat(config.plugins),
  }
 );
}

module.exports = function(env){
 console.log("env",env);
 if(env=='development'){
  return developmentConfig();
 }
 return commonConfig;
};
Copy after login

Regarding Object.assign, the first parameter is the target object, if the properties in the target object have the same key, the properties will be assigned by the ones in the source Property override. Properties of later sources will similarly override earlier properties. Shallow assignment, use = for object copying, that is, reference copying.

The env parameter is passed in through cli.

Then open the command line to the current directory and run npm start or npm run build. Note that the former is in the development environment and has no output file (in memory). Only when the latter is run will there be an output file.

The code of the demo is at: https://github.com/yuwanlin/webpackHMR

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Sharing the three parsing modes of ajax


##Comparing the three implementations of Ajax and JSON parsing


Discuss .get .post .ajax ztree and the related knowledge of background servlet transferring data


The above is the detailed content of Webpack hot module replacement (HMR)/hot update method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template