Home  >  Article  >  Web Front-end  >  How webpack implements hot module replacement

How webpack implements hot module replacement

php中世界最好的语言
php中世界最好的语言Original
2018-05-02 10:49:121290browse

This time I will show you how webpack implements hot module replacement, and what are the precautions for webpack to implement hot module replacement. The following is a practical case, let's take a look.

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: (Required to complete hot update)

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

The following is the 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"
 }
}

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

config file

, you can also modify the configuration of 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;
};
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 overwritten by the properties in the source. Properties of later sources will similarly override earlier properties. Shallow assignment, use = for copying objects, that is,

reference

copy. 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.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Mint-ui usage steps detailed explanation


What are the properties of JS to determine whether there is a scroll bar on the page?


Six commonly used JS sorting algorithms and comparison

The above is the detailed content of How webpack implements hot module replacement. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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