webpackmernwebpack-dev-middlewarewebpack-hot-middleware

Bundle created by webpack does not reflect changes on the browser after successful compilation


I am running a very very simple code of stack. I am using and . The problem is when I run node server.js, compilation works without error but I don't see any change I make on my client side code on the browser, the browser doesn't even refresh itself even with the hot module. Maybe both of the above problem are because of something I am missing in the code.

Edited: My program is pulling the bundle from disk when I use webpackdevmiddleware. e.g. Lets say if I empty my bundle.js then my browser is actually pulling an empty file even when the server is on, it can watch file changes and successfully compiles it but the browser doesn't reflect them. Feels like the browser is not pulling it from any memory but from the disk.

Webpack.config.js:

const path = require('path');
const webpack = require("webpack")

module.exports = {
    mode: "production",
    entry: {
        app: [__dirname + "/static/jsx/core-jsx/app3.jsx"],
        vendor: ["react", "react-dom", "whatwg-fetch"],
    },
   
    plugins: [
        //new webpack.optimize.CommonsChunkPlugin({name:"vendor",filename: "vendor.bundle.js"}),
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    module: {
        rules: [
            {
                test: /\.jsx$/,
                loader: 'babel-loader',
            }
        ]
    },
    devServer: {
        hot:true,
        port: 8000,
        contentBase: "static",
        proxy: {
            '/api/*': {
                target: "http://localhost:3000/",
                changeOrigin: true
            },

        }
    },
    devtool: "source-map",
    resolve: {
        alias: {
            jsx: path.resolve(__dirname, 'static/jsx/core-jsx')
        },

    },
     output: {
        path: __dirname + '/static/jsx',
        filename: 'app.bundle.js',
        publicPath: '/',
    }
}

Server.js

    if (process.env.NODE_ENV !== 'production') {
    const webpack = require('webpack');
    const webpackDevMiddleware = require('webpack-dev-middleware');
    const webpackHotMiddleware = require('webpack-hot-middleware');
    const config = require('./webpack.config');
    const bundler = webpack(config);
    app.use(webpackDevMiddleware(bundler, {
        noInfo: true,
        publicPath: config.output.publicPath,
    }));
    app.use(webpackHotMiddleware(bundler));
    
}

enter image description here

Add my dev tools screenshot enter image description here


Solution

  • It seems I made a few errors. I made it work now. Below is my code

    webpack.config.js

    const path = require('path');
    var HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
        watch: true,
        mode: 'development',
        entry: {
    
            "app": ["webpack-hot-middleware/client?path=/__webpack_hmr", __dirname + "/static/jsx/core-jsx/app3.jsx", "react", "react-dom", "whatwg-fetch"],
    
    
        },
        module: {
            rules: [
                {
                    test: /\.jsx$/,
                    loader: 'babel-loader',
                }
            ]
        },
        devServer: {
            contentBase: path.resolve(__dirname, '/static/'),
    
        },
        devtool: "source-map",
        resolve: {
            alias: {
                jsx: path.resolve(__dirname, 'static/jsx/core-jsx')
            },
    
        },
        output: {
            path: __dirname + '/static/',
            filename: 'app.bundle.js',
            publicPath: '/',
        },
        optimization: {
            splitChunks: {
                chunks: "all",
            }
        },
        plugins: [
            new HtmlWebpackPlugin({
                filename: "index.html",
                inject: "head",
                templateContent: `<html>
          <body>
            <div id="contents"></div>
          </body>
        </html>`
            }),
    
        ],
    }
    

    Server.js

        const express = require("express");
    const path = require('path');
    
    
    const app = express();
    const bodyParser = require('body-parser');
    
    app.use(express.static("static"));
    
    app.use(bodyParser.json());
    
    
    
    const MongoClient = require("mongodb").MongoClient;
    const Issue = require("./server/issue.js");
    
    let db;
    
    
    
    if (process.env.NODE_ENV !== 'production') {
    
        const webpack = require('webpack');
    
        const webpackDevMiddleware = require('webpack-dev-middleware');
        const webpackHotMiddleware = require('webpack-hot-middleware');
    
    
        const config = require('./webpack.config');
        config.plugins.push(new webpack.HotModuleReplacementPlugin())
        const compiler = webpack(config);
        app.use(webpackDevMiddleware(compiler, {
            inline: true,
            publicPath: config.output.publicPath,
            noInfo: true,
        }));
    
    
    
        app.use(webpackHotMiddleware(compiler, {
            path: '/__webpack_hmr',
            heartbeat: 10 * 1000,
            log: console.log,
    
        }));
    
    
    
    }
    
    
    MongoClient.connect("mongodb://localhost", {
        useUnifiedTopology: true
    }).then(connection => {
    
        db = connection.db("issuetracker");
    
        app.listen(3000, () => {
    
            console.log("App started on port 3000");
    
        });
    
    }).catch(error => {
    
        console.log("Error: ", error);
    });
    
    
    
    
    
    
    app.post('/api/issues', (req, res) => {
    
        const newIssue = req.body;
    
    
        newIssue.created = new Date();
    
        if (!newIssue.status) {
    
            newIssue.status = "New";
        }
    
        const err = Issue.validateIssue(newIssue)
    
        if (err) {
            res.status(422).json({
                message: `Invalid request:  ${err}`
            });
            return;
    
        }
    
        db.collection("issues").insertOne(newIssue).then(result => db.collection("issues").find({
            _id: result.insertedId
        }).limit(1).next()).then(newIssue => {
    
            res.json(newIssue);
    
    
        }).catch(error => {
    
            console.log(error);
    
            res.status(500).json({
                message: `Internal Server Error: ${error}`
            });
    
        });
    
    })
    
    
    
    app.get('/api/issues', (req, res) => {
    
        db.collection("issues").find().toArray().then(issues => {
    
            const metadata = {
                total_count: issues.length
            };
    
            res.json({
                _metdata: metadata,
                records: issues
            })
    
        }).catch(error => {
    
            console.log(error);
            res.status(500).json({
                message: `internal Server Error: ${error}`
            });
    
        });
    
    });
    

    There are so many questions unanswered with this topic. I hope it helps someone.