Hot module replacement (HMR) or hot loading is a feature of webpack allowing real time update of modules while the application is running, which could significantly speed up development.
Enable Hot module replacement
Goal: To enable HMR in the React application in a simple setup.
Base project code: Example code from React with Typescript, Get started with ASP.NET Core serves as starting point. (Rendering a simple HelloWorld typescript component)
Npm packages
Add the following package to “dependencies” in file package.json
1 |
"react-hot-loader": "4.3.4" |
and the following 2 packages to “devDependencies”
1 2 |
"@types/react-hot-loader": "4.1.0", "webpack-hot-middleware": "2.22.3" |
webpack-hot-middleware and react-hot-loader are packages to support hot module replacement.
Update entry.tsx (bundle entry file)
Update file entry.tsx in folder Scripts with code below:
1 2 3 4 5 6 7 8 9 10 |
import * as React from 'react'; import { render } from 'react-dom'; import { HelloWorld } from './HelloWorld'; import { hot } from 'react-hot-loader'; var HotHelloWorld = hot(module)(HelloWorld); var App = () => <HotHelloWorld />; render(<App />, document.querySelector('#content')); |
Use hot() from package react-hot-loader to wrap around the HelloWorld component to support hot loading.
Update Startup.cs
Replace app.UseWebpackDevMiddleware() with the following code:
1 |
app.UseWebpackDevMiddleware(new Microsoft.AspNetCore.SpaServices.Webpack.WebpackDevMiddlewareOptions { HotModuleReplacement = true }); |
This adds WebpackDevMiddlewareOptions to enable HMR.
That’s it! The application should run as normal. Now modify HelloWorld and simply save the file will update the application automatically.
Additional Notes
If HMR does not work properly on your project after following the steps here, you may want to try adding react-hot-loader/babel plugin for babel-loader . Check out instructions from react-hot-loader.
Example code is available at Github.