Hot Module Replacement
HMR is very interesting topic now a days because it is making development significantly faster. HMR adds, exchanges or removes a module while running an application without full reload.
Why Hot Module Replacement?
It increases the productivity because we were about to break our F5 key before.
Configuring HMR (Hot Module Replacement)
You need to start level zero to understand the configuration, I suppose, you may be aware of many of followings:
mkdir react-hmr-configuration
cd react-hmr-configurationnpm init
// enter all information for related to your projectnpm install -g webpack
npm install --save-dev webpack// now install webpack dev server to run your project
npm install webpack-dev-server -g
npm install webpack-dev-server --save-dev// installing react
npm i babel-core babel-loader@7 babel-preset-es2015 babel-preset-react --save-dev
Create webpack.config.js in the root of project then copy + paste this:
module.exports = {
entry: "./index.js",
output: {
path: __dirname,
filename: "bundle.js",
publicPath: "/static/"
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "babel-loader",
query: {
presets: ["es2015", "react"]
}
}
}
]
}
};
Create index.html and copy + paste this
<!DOCTYPE html>
<html>
<head>
<title>React HMR Example</title>
</head>
<body>
<div id="container"></div>
<script src="/static/bundle.js"></script>
</body>
</html>
Create src/components/App.js
import React, { Component } from "react";export default class App extends Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
} componentDidMount() {
this.interval = setInterval(this.increment.bind(this), 1000);
} increment() {
this.setState(({ counter }) => {
return { counter: counter + 1 };
});
} componentWillUnmount() {
clearInterval(this.interval);
} render() {
const { counter } = this.state; return (
<header>
<div>React Component</div>
<div>{counter}</div>
</header>
);
}
}
Edit your package.json
"scripts": {
"start": "webpack-dev-server --progress --inline"
},
Now add entry point index.js and copy + paste the following
import { render } from "react-dom";
import React from "react";
import App from "./src/components/App";const reactContainerElement = document.getElementById("container");render(<App />, contreactContainerElementainerEl);
All done, now run the command npm start
and to test your HMR is working fine or not please change the content of you index.js and it will update the changes without breaking your F5 key.