Home > Article > Web Front-end > What is the usage of react-hot-loader
"react-hot-loader" is used to automatically refresh the modified parts when using react to write code; "hot-loader" does not refresh the web page, but replaces the modified parts. You can use "npm install --save-dev react-hot-loader" installation.
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
What does hot loader do? A quote from the official website is
To put it simply, when you use react to write code, the modified parts can be automatically refreshed.
But this is different from automatically refreshing the web page, because hot-loader does not refresh the web page, but only replaces the parts you modified.
Installation
The first step is to install react-hot-loader
npm install --save-dev react-hot-loader
In addition, hot-loader is based on webpack-dev-server, so it must be installed webpack-dev-server
npm install --save-dev webpack-dev-server
Configuration
Configuration webpack-dev-server
When using react-hot-loader, you must first let webpack -dev-server is turned on.
Create a new server.js in the root directory
var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var config = require('./webpack.config'); new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, historyApiFallback: true }).listen(3000, 'localhost', function (err, result) { if (err) { return console.log(err); } console.log('Listening at http://localhost:3000/') }); 配置 webpack.config.js 然后在 webpack 的配置文件里添加 react-hot-loader。 打开 webpack.config.js var webpack = require('webpack'); module.exports = { // 修改 entry entry: [ // 写在入口文件之前 "webpack-dev-server/client?http://0.0.0.0:3000", "webpack/hot/only-dev-server", // 这里是你的入口文件 "./src/app.js", ], output: { path: __dirname, filename: "build/js/bundle.js", publicPath: "/build" }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, // 在这里添加 react-hot,注意这里使用的是loaders,所以不能用 query,应该把presets参数写在 babel 的后面 loaders: ['react-hot', 'babel?presets[]=react,presets[]=es2015'] } ] }, // 添加插件 plugins: [ new webpack.HotModuleReplacementPlugin() ]
Use
First run server.js (of course you can configure it in package.json, use npm start run)
node server.js
Then use webpack as usual
webpack --display-error-details --progress --colors --watch
Recommended learning: "react video tutorial"
The above is the detailed content of What is the usage of react-hot-loader. For more information, please follow other related articles on the PHP Chinese website!