简体   繁体   中英

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:

错误

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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM