'how to configure webpack HMR with express

package.json scripts:

 "scripts": {
    "build": "webpack --config config/webpack.prod.config.js",
    "dev": "webpack --config config/webpack.dev.config.js && nodemon ./dist/server.js",
    "start": "nodemon ./dist/server.js"
  }

and this is main file:

server.js

import express from "express";
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './config/webpack.dev.config';

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

app.get("/", (req, res) => {
    res.send("Hello");
});

app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));

app.listen(4000, () => console.log("Listening to port 4000"))

my webpack config divided in three files:

  • config/webpack.common.config.js
  • config/webpack.dev.config.js
  • config/webpack.prod.config.js

this is webpack common config:

webpack.common.config.js

module.exports = {
    entry: {
        server: './server.js'
    },
    output: {
        path: path.join(__dirname, '../dist'),
        publicPath: "/",
        filename: '[name].js'
    },
    target: 'node',
    externals: [new nodeExternals()],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin()
    ]
}

this is webpack dev config:

webpack.dev.config.js

module.exports = merge(common, {
    entry: {
        server: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './server.js']
    },
    mode: 'development',
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ]
})

this is webpack dev config:

webpack.prod.config.js

module.exports = merge(common, {
    mode: 'production'
});

finally this is the error:

error

what is the problem? how to config the hot reload in webpack and express?



Solution 1:[1]

add "devServer" property to your webpack:

devServer: {
    contentBase: "dist",
    hot: true,
    stats: { colors: true }
  },

then add this to the entry point of webpack. in your project it is server.js

 require("webpack-hot-middleware/client?reload=true");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yilmaz