webpack configuration react-hot-loader hot load local update
Some people may ask that webpack-dev-server is already hot loading, and the page can be automatically updated as long as the code is modified. Why do you need to install react-hot-loader in the react project?
In fact, there is a difference in the updates between the two. The hot loading of webpack-dev-server is caused by the developer modifying the code, and the code is packaged and refreshing the entire page.
react-hot-loader will not refresh the entire page, it only replaces the modified code, and achieves partial refresh of the page.
But it needs to rely on webpack's HotModuleReplacement hotloading plugin.
Let’s talk about how to configure react-hot-loader.
Step 1
Install react-hot-loader
npm install --save-dev react-hot-loader
Step 2
Add react-hot-loader/patch to the entry value, and be sure to write it at the front of the entry. If there is a babel-polyfill, write it in
The back of the babel-polyfill.
entry: [ 'babel-polyfill', 'react-hot-loader/patch', //Set here __dirname + '/app/' ]
Step 3
Set the hot of devServer to true in
devServer: { contentBase: './build', port: '1188', historyApiFallback: true, inline: true, hot: true, //Set here },
Step 4
Add plugin in .babelrc
{ "presets": ['es2015', 'react'], "plugins": ["react-hot-loader/babel"] //Set here}
Step 5
Add dependency HotModuleReplacement plugin in plugins
plugins: [ new HtmlWebpackPlugin({ template: __dirname + "/app/" }), new () //Set here]
Step 6
The last operation is to add some code to the main entrance of the project, for example, mine is
import React from 'react'; import ReactDOM from 'react-dom'; import Greeter from './greeter'; import "./"; import { AppContainer } from 'react-hot-loader'; //Set here const render = (App) => { ( <AppContainer> <App /> </AppContainer>, ('root') ) } render(Greeter) // Hot Module Replacement API if (module && ) { ('./greeter', () => { render(require('./greeter').default) }) }
I tried this and it worked.
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app'; import "./"; ( <App />, ('root') ) if (module && ) { () }
Complete the above 6 steps in order. Congratulations, React's react-hot-loader has been configured.
Possible problem of react-hot-loader hot loading not taking effect
If this is the following, no hot loading will be performed
const AsyncLogin = asyncComponent(() => import("./Login")); //I can't load itimport home from './home' //I can load it<Route exact path='/' component={home}/> <Route path='/login' component={AsyncLogin}/> <Route path='/home' component={home}/>
In other words, components need to be introduced synchronously to be successfully loaded locally
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.