javascript - 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,您可以(可能)在此处查看代码沙箱,看看您是否可以复制这种奇怪的行为。
解决方案
发生的事情是,您将dist
目录中的所有文件作为静态文件提供,您index.html
的文件由 html-webpack-plugin 生成。我不确定如何在 express 中处理路径,但似乎静态文件优先于定义的任何路由,这就是为什么dist/index.html
要覆盖/
路径。
推荐阅读
- yargs - 我在哪里可以找到 yargs npm 中的 builder 文档?
- sql-server - 表值参数连接性能
- postgresql - 如何在 crunchydata postgres 运算符中使用 nfs 存储
- c# - DataGridView 在使用异步填充后隐藏滚动条
- bash - 使用 bash 删除配置文件中的部分
- python - R 中 12 个 excel 工作簿的数据合并(每个包含 3 个工作表)
- c# - 如何使游戏对象实体化
- frida - ssdeep 模糊哈希和 frida 服务器二进制文件
- react-native - 我在 6 个月前为 cognito 注册配置了 aws-amplify sdk。我想更新它以进行社交注册(谷歌)
- java - 自动生成包含泛型类型的构建器模式