首页 > 解决方案 > html-webpack-plugin 是否在劫持我的快递服务器?

问题描述

我一直在学习https://webpack.js.org/guides/output-management/上的教程,它们巩固了我对 webpack 通常如何将整个前端捆绑到由准系统 HTML 运行的脚本的理解像这样的页面:

<html>
<head>
    <title>Output Management</title>
</head>
<body>
    <script src="./app.bundle.js"></script>
</body>
</html>

该文件位于项目根目录中的 src 目录中。

我通过从 Express 服务器提供 HTML 页面对教程稍作修改,如下所示:

const express = require("express");
var path = require("path");

const server = express();
server.use(express.static(path.join(__dirname, "../dist")));
server.use(express.urlencoded({ extended: true }));

var indexPath = path.join(__dirname, "../src/index.html");

//create a server object:
server
    .get("/", function(req, res) {
        res.status(200)
        res.sendFile(indexPath);
        //res.send('<h1>I am not the webpack script!</h1>')
    })

module.exports = server

到目前为止,一切都说得通。该服务器为我的 index.html 提供服务,它运行 webpack 脚本,该脚本使 HTML 页面显示一些文本、图像和 CSS。如果我取消注释 res.send 行,服务器将改为提供单行网站。

但是,链接的教程建议尝试 HTML-webpack 插件,当它出现时我会感到困惑。我了解该插件在与捆绑脚本(在我的情况下为 /dist)相同的目录中创建了一个 index.html 文件,该文件包含由 webpack 创建的所有脚本。当然,有道理。但是没有任何东西明确地提供该 HTML 文件。但是,如果我将插件添加到我的 webpack 配置中:

    entry: {
        app: "./src/index.js",
        print: "./src/print.js"
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: 'Output Management',
+     }),
+   ],
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, "dist")
    },

然后在浏览器中导航到 localhost:3000,它会显示 /dist/index.html 文件,而不是 /src/index.html 文件。我没有做任何修改 server.js 文件会改变浏览器中显示的内容,但是如果我停止收听该服务器,我什么也看不到,所以显然 webpack-html-plugin 没有创建自己的服务器。

所以看起来正在发生的事情是 webpack-html-plugin 不仅仅是动态创建一个 HTML 文件来运行捆绑的脚本,它还在以一种我没有明确指示并且似乎无法修改的方式改变我的服务器的行为。

TLDR:具体来说,webpack-html-plugin 中的某些内容导致我的 express 服务器的根路由服务于 /dist/index.html,而不是我明确指示的 /src/index.html。为什么?

回购位于https://github.com/CliffRobinson/webpack-tutorial-sandbox,您可以(可能)在此处查看代码沙箱,看看您是否可以复制这种奇怪的行为。

标签: javascriptnode.jsexpresswebpack

解决方案


发生的事情是,您将dist目录中的所有文件作为静态文件提供,您index.html的文件由 html-webpack-plugin 生成。我不确定如何在 express 中处理路径,但似乎静态文件优先于定义的任何路由,这就是为什么dist/index.html要覆盖/路径。


推荐阅读