Home Web Front-end JS Tutorial How webpack implements hot module replacement

How webpack implements hot module replacement

May 02, 2018 am 10:49 AM
web webpack replace

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);
}
Copy after login

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"
 }
}
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

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Master PyCharm replacement shortcut keys in 5 minutes and easily increase your programming speed! Master PyCharm replacement shortcut keys in 5 minutes and easily increase your programming speed! Feb 22, 2024 am 10:57 AM

Master PyCharm replacement shortcut keys in 5 minutes and easily increase your programming speed!

Replace the class name of an element using jQuery Replace the class name of an element using jQuery Feb 24, 2024 pm 11:03 PM

Replace the class name of an element using jQuery

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions

PyCharm replaces shortcut keys to make programming more convenient! PyCharm replaces shortcut keys to make programming more convenient! Feb 21, 2024 pm 12:03 PM

PyCharm replaces shortcut keys to make programming more convenient!

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

How to enable administrative access from the cockpit web UI

Revealing the secret of how to quickly replace code in PyCharm Revealing the secret of how to quickly replace code in PyCharm Feb 25, 2024 pm 11:21 PM

Revealing the secret of how to quickly replace code in PyCharm

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

Is PHP front-end or back-end in web development?

How to replace a word in Excel using Python? How to replace a word in Excel using Python? Sep 16, 2023 pm 10:21 PM

How to replace a word in Excel using Python?

See all articles