Specific steps for replacing HMR/hot updates with webpack's hot modules
This time I will bring you the specific steps of replacing HMR/hot update with webpack's hot module. What are the precautions for replacing HMR/hot update with webpack's hot module. The following is a practical case. Let's take a look. take a look.
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 that when the application is running, necessary modules can be replaced, added, or deleted without refreshing the page. 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:
app
- ##a.js
- component.js
- index.js
- node_modules
- package.json
- webpack.config.js ##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 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
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:
How to use JS to determine whether the current page has scroll barsmint-ui in vue InstructionsThe above is the detailed content of Specific steps for replacing HMR/hot updates with webpack's hot modules. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
