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

1

0

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

Streamer answered 17/7, 2020 at 16:8 Comment(8)
wild guess : #40903538 the issue in this link somewhat related to what you report. maybe its relevant to what you face?Deep
Thanks but no. So in devTools, I checked the sources tab. I see 2 clouds icons 1) localhost:3000- the local directory 2) webpack - I assume its the server memory. I somehow don't see bundle.js on webpack memory which is very strange isn't it? I wonder where does the file go.Streamer
hmmm.. i get totally diff stack in devtools from running "webpack-dev-server" on a non-react project that is node & webpack AND i dont have occaision to look down at the cloud <-> webpack . i just use "index" and "main.bundle.js" . so i can only say i am not clear on what u are actully running??Deep
i looked at the pic of your stack and compare to what devtools shows of my stack where HMR is working fine.... i do NOT see anything that jumps out at me.. Im not HMR expert or webpack dev server expert .Deep
YEs, I see that too from here #45866294 But it is still unclear - where does my file goes after compilation because the file in the sources is not getting updated. E.g. I put console.log("hello") in one of my JSX file. THe webpack compiles it but when I open the bundle in the sources the update isn't there.Streamer
my example is not of much use as im using webpack-dev-server and you are using the middleware approach.Deep
github.com/gaearon/react-hot-loader/issues/79 if HMR is OK the default is to get logs onRecompileDeep
no I am sorry doesn't help. I have seen too many websites and too many solutions. Its mind boggling that nothing works.Streamer
S
0

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.

Streamer answered 22/7, 2020 at 12:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.