成功编译后,由webpack创建的捆绑包不会反映浏览器上的更改 [英] Bundle created by webpack does not reflect changes on the browser after successful compilation

查看:105
本文介绍了成功编译后,由webpack创建的捆绑包不会反映浏览器上的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行非常简单的.问题是当我运行node server.js时,编译工作没有错误,但是我没有在浏览器上的客户端代码上进行任何更改,即使使用热模块,浏览器也无法刷新自身.也许以上两个问题都是由于代码中缺少某些内容.

I am running a very very simple code of mern stack. I am using webpack-dev-middleware and webpack-hot-middleware. 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.

当我使用webpackdevmiddleware时,我的程序正在从磁盘中拉出捆绑包.例如可以说,如果我清空bundle.js,那么即使服务器开启,我的浏览器实际上也会拉出一个空文件,它可以监视文件更改并成功编译它,但浏览器无法反映它们.感觉浏览器不是从任何内存中而是从磁盘中提取它.

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:

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

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

添加我的开发工具屏幕截图

Add my dev tools screenshot

推荐答案

似乎我犯了一些错误.我现在使它工作了.下面是我的代码

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

webpack.config.js

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

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.

这篇关于成功编译后,由webpack创建的捆绑包不会反映浏览器上的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆