Table of contents

  1. 1. Setup
  2. 2. Tested with

Programmatically setup an Express server with Webpack’s Hot Module Replacement (HMR) to host a React web application.

Setup

Your Express server can become a webpack development server when configuring it the following way:

server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import express from 'express';
import {HotModuleReplacementPlugin, webpack} from 'webpack';

const app = express();

const webpackCompiler = webpack({
entry: ['webpack-hot-middleware/client', `${__dirname}/webapp/App.tsx`],
mode: 'development',
module: {
rules: [
{
exclude: /node_modules/,
test: /.[tj]sx?$/,
use: {
loader: 'babel-loader',
options: {
plugins: ['@babel/plugin-proposal-class-properties'],
presets: ['@babel/preset-react', '@babel/preset-typescript'],
},
},
},
],
},
plugins: [
new HotModuleReplacementPlugin(),
],
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
});

const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

app.use(webpackDevMiddleware(webpackCompiler));
app.use(webpackHotMiddleware(webpackCompiler));

app.use(express.static(`${__dirname}/webapp`));

const port = 3000;

app.listen(3000, async () => {
console.log(`Started server on port "${port}".`);
});

The above configuration will server your web application from the static directory “webapp”. Your “webapp” directory must contain the “index.html” file of your React web application:

webapp/index.html
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script src="main.js"></script>
</body>
</html>

If you want to trigger the “Hot Module Replacement” feature from your React web page, you will have to activate “module.hot”:

webapp/App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
import React from 'react';
import ReactDOM from 'react-dom';
import App from './page/App';

function runApp(): void {
if (module.hot) {
module.hot.accept();
ReactDOM.render(<App />, document.getElementById('root'));
}
}

runApp();

Tested with