Webpack Hot Middleware

2.26.1 · active · verified Sun Apr 19

Webpack Hot Middleware provides hot module replacement (HMR) capabilities for Webpack applications by integrating with an existing server, such as Express, and `webpack-dev-middleware`. This library is a direct alternative to `webpack-dev-server` for scenarios where developers need more control over their server setup, particularly for integrating HMR into custom backend environments. It focuses exclusively on the client-server communication mechanism for HMR updates, subscribing to server-side changes and executing them using Webpack's native HMR API. The current stable version is 2.26.1, released in February 2024, indicating a steady but infrequent release cadence primarily for bug fixes and compatibility updates. It does not handle the actual component-level hot reloading, leaving that to other libraries like React Hot Loader.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `webpack-hot-middleware` with Express and `webpack-dev-middleware`. It includes a basic Webpack configuration, an Express server, and a client-side entry point (`src/main.js`) with simple HMR acceptance logic.

/* webpack.config.js */
const webpack = require('webpack');
const path = require('path');

module.exports = {
  mode: 'development',
  entry: {
    main: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './src/main.js'],
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    // new webpack.NoEmitOnErrorsPlugin() // Optional: Uncomment for cleaner error handling, but may hide issues
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: { presets: ['@babel/preset-env'] }
        }
      }
    ]
  }
};

/* server.js */
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('./webpack.config');

const app = express();
const compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
  publicPath: webpackConfig.output.publicPath,
  stats: { colors: true },
}));

app.use(webpackHotMiddleware(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000,
}));

app.get('/', (req, res) => {
  res.send(`
    <!DOCTYPE html>
    <html>
    <head><title>Webpack Hot Middleware</title></head>
    <body>
      <h1>Hello Webpack Hot Middleware!</h1>
      <div id="root"></div>
      <script src="/main.bundle.js"></script>
    </body>
    </html>
  `);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

/* src/main.js */
import './styles.css'; // Assume you have a simple css file

console.log('App started!');

const root = document.getElementById('root');
let count = 0;
function render() {
  root.innerHTML = `Count: ${count++}`;
}

render();

if (module.hot) {
  module.hot.accept('./main.js', function() {
    console.log('Accepting updated main.js!');
    render();
  });
  module.hot.accept('./styles.css', function() {
    console.log('Accepting updated styles.css!');
  });
}

view raw JSON →