簡體   English   中英

webpack 創建的 Bundle 編譯成功后在瀏覽器上沒有反映變化

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

我正在運行一個非常簡單的堆棧代碼。 我正在使用 問題是當我運行node server.js時,編譯工作沒有錯誤,但我沒有看到我在瀏覽器上對客戶端代碼所做的任何更改,即使使用熱模塊,瀏覽器也不會自行刷新。 也許上述兩個問題都是因為我在代碼中遺漏了一些東西。

編輯:當我使用 webpackdevmiddleware 時,我的程序正在從磁盤中提取包。 例如,如果我清空我的 bundle.js,那么即使服務器打開,我的瀏覽器實際上也會拉出一個空文件,它可以觀察文件更改並成功編譯它,但瀏覽器不會反映它們。 感覺瀏覽器不是從任何 memory 而是從磁盤中提取它。

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

在此處輸入圖像描述

添加我的開發工具截圖在此處輸入圖像描述

看來我犯了一些錯誤。 我現在讓它工作了。 下面是我的代碼

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

    });

});

這個話題有很多問題沒有答案。 我希望它可以幫助某人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM