【问题标题】:webpack-hot-middleware not serving any filewebpack-hot-middleware 不提供任何文件
【发布时间】:2019-09-26 05:02:46
【问题描述】:

我按照webpack-hot-middleware 的 GitHub 页面上的教程进行操作,但我无法让它工作。我在浏览器中收到下一个:index.bundle.js:1 Uncaught SyntaxError: Unexpected token < 因为找不到文件。我知道webpack-dev-middleware 在内存中提供文件,但我不知道如何使它工作。

这里是 server.js:

//...

var webpack = require('webpack');
var webpackConfig = require('./../webpack.config');
var compiler = webpack(webpackConfig);

console.log("QQQ", webpackConfig.output.publicPath);

app.use(require("webpack-dev-middleware")(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath
}));
app.use(require("webpack-hot-middleware")(compiler, {
    log: console.log,
    path: '/__webpack_hmr',
    heartbeat: 10 * 1000
}));

//...

app.get('*', async (req, res) => {
    //...

    res.render('index', {
        //...
    });
});

const server = new http.Server(app); // Create a server through Express
server.listen(process.env.NODE_PORT, err => {
    if (err) {
        return console.error(err);
    }
    console.info(`Server running on http://localhost:${process.env.NODE_PORT}`);
});

这里是index.ejs

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui" />

        <base href="/">

        <meta name="keywords" content="<%- keywords %>" />
        <meta name="description" content="<%- description %>" />
        <title><%- title %></title>

        <!-- ... -->

        <!-- PRERENDER:DELETE -->
        <script defer src="/js/index.bundle.js"></script>
        <script defer src="/js/vendor.chunk.js"></script>
        <!-- PRERENDER:END -->

        <%- headOther.toString() %>
    </head>
    <body>
        <div id="main"></div>
    </body>
</html>

最后是webpack.config.js:

const webpack = require("webpack");
const path = require("path");

const isProduction = process.env.NODE_ENV === "production";

module.exports = {
    mode: isProduction ? "production" : "development",
    entry: {
        index: [
            "webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000",
            path.join(__dirname, "src", "client.js")
        ]
    },
    context: path.join(__dirname, "src"),
    output: {
        path: path.join(process.env.IMOCENTRAL_SITE_DATA, "static"),
        publicPath: "/js/",
        chunkFilename: "js/[name].chunk.js",
        filename: "js/[name].bundle.js"
    },
    devtool: isProduction ? undefined : "cheap-module-eval-source-map",
    module: {
        rules: [
            {
                test: /\.js?$/,
                exclude: [/node_modules/, /\.tem\.js$/],
                loader: "babel-loader",
                options: {
                    cacheDirectory: "babel_cache",
                    presets: ["@babel/react", ["@babel/env", { modules: false, useBuiltIns: "usage", corejs: 2 }]],
                    plugins: [
                        ["@babel/plugin-syntax-object-rest-spread"],
                        ["@babel/plugin-syntax-async-generators"],
                        ["@babel/plugin-transform-regenerator"],
                        ["@babel/plugin-syntax-dynamic-import"],
                        ["@babel/plugin-proposal-class-properties"],
                        ["react-hot-loader/babel"]
                    ]
                }
            },
            //...
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            __production: isProduction ? "true" : "false",
            'process.env.NODE_ENV': JSON.stringify(isProduction ? "production" : "development"),
            AppConfig: JSON.stringify(require("./src/data/MainData").default)
        }),
        new webpack.HotModuleReplacementPlugin()
    ],
    optimization: {
        splitChunks: {
            chunks: "all",
            maxInitialRequests: Infinity,
            minSize: 0,
            cacheGroups: {
                vendor: {
                    test: /node_modules/,
                    chunks: "initial",
                    name: "vendor",
                    enforce: true
                }
            }
        }
    },
    resolve: {
        modules: [path.resolve(__dirname, "src"), path.join(__dirname, "node_modules")],
        alias: {
            ExternalStyles: path.join(process.env.IMOCENTRAL_SITE_DATA, "styles")
        },
        extensions: [".js", ".jsx"]
    },
    externals: {
        fs: "{}",
        tls: "{}",
        net: "{}",
        console: "{}",
        v8: "{}"
    }
}

IMOCENTRAL_SITE_DATA 是项目文件夹之外的位置。

【问题讨论】:

    标签: javascript express webpack hot-reload


    【解决方案1】:

    我在 MEAN 堆栈项目中遇到了类似的错误。 app.get 方法最初只有 index.html 文件的路径。当我在 Chrome 开发者工具控制台选项卡中点击导致错误的文件名时,它显示在查找 js 文件时,它只找到了 index.html 文件:

    Chrome dev tools Console Chrome dev tools Sources

    我不确定我的解决方案是否与您的相同,因为我没有使用 webpack,而且我也是 MEAN/express 的新手 :) 但以防万一,最后一个答案 here帮我修好了。

    即添加到 server.js:

        const allowed = [
      '.js',
      '.css',
      '.png',
      '.jpg'
    ];
    
    app.get('*', function(req, res) {       
        if (allowed.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
          res.sendFile(path.resolve(`dist/meantodo/${req.url}`));
       } else {
          res.sendFile(path.join(__dirname, 'dist/meantodo/index.html'));
       }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 2016-05-25
      • 2018-02-26
      • 2017-07-06
      • 2020-06-07
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      相关资源
      最近更新 更多