0

我正在运行一个非常简单的堆栈代码。我正在使用。问题是当我运行时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));
    
}

在此处输入图像描述

添加我的开发工具截图 在此处输入图像描述

4

1 回答 1

0

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

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-07-22T12:21:23.867 回答