【问题标题】:Bundle created by webpack does not reflect changes on the browser after successful compilationwebpack 创建的 Bundle 编译成功后在浏览器上没有反映变化
【发布时间】:2020-07-17 16:08:28
【问题描述】:

我正在运行一个非常简单的 堆栈代码。我正在使用。问题是当我运行node server.js 时,编译工作没有错误,但我没有看到我对浏览器上的客户端代码所做的任何更改,即使使用热模块,浏览器也不会自行刷新。也许上述两个问题都是因为我在代码中缺少一些东西。

已编辑:当我使用 webpackdevmiddleware 时,我的程序正在从磁盘中提取包。例如可以说,如果我清空 bundle.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: '/',
    }
}

服务器.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));
    
}

添加我的开发工具截图

【问题讨论】:

  • 疯狂猜测:stackoverflow.com/questions/40903038/… 此链接中的问题与您报告的内容有些相关。也许它与你所面对的有关?
  • 谢谢,但没有。所以在 devTools 中,我检查了源选项卡。我看到 2 个云图标 1) localhost:3000- 本地目录 2) webpack - 我假设它是服务器内存。我不知何故在 webpack 内存上看不到 bundle.js,这很奇怪不是吗?我想知道文件在哪里。
  • hmmm .. 我在 devtools 中完全不同的堆栈来自在节点和 webpack 的非反应项目上运行“webpack-dev-server”并且我没有机会低头看云 网络包。我只使用 "index" 和 "main.bundle.js" 。所以我只能说我不清楚你到底在做什么??
  • 我查看了您的堆栈图片,并与 devtools 显示的堆栈中 HMR 工作正常的内容进行了比较......我没有看到任何让我兴奋的东西......我不是 HMR 专家或 webpack 开发服务器专家。
  • 我的示例没有多大用处,因为我使用 webpack-dev-server 并且您使用的是中间件方法。

标签: mern webpack-dev-middleware webpack-hot-middleware webpack mern webpack-dev-middleware webpack-hot-middleware


【解决方案1】:

看来我犯了一些错误。我现在让它工作了。下面是我的代码

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>`
        }),

    ],
}

服务器.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}`
        });

    });

});

这个话题有很多问题没有答案。我希望它可以帮助某人。

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 2019-11-24
    • 2017-11-14
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    相关资源
    最近更新 更多