在 PHP 中,您可以包含文件片段以方便重用。在下面的示例中,我可以包含 header.php
和 footer.php
。这非常方便,因为当我更新 header.php
时,更改会显示在使用它的所有页面上:
<html>
<body>
<?php include 'header.php';?>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
我已经成功尝试了该方法 in this answer使用 html-webpack-plugin
,但有一个问题。请参阅下面我的配置:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const fs = require("fs");
module.exports = () => ({
// ... lots of Webpack boilerplage
module: {
rules: [
// ... js, sass, json, etc loaders
]
},
plugins: [
//...
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: "./static/index.html",
header: fs.readFileSync(htmlPath + "/header.html"),
footer: fs.readFileSync(htmlPath + "/footer.html"),
filename: "index.html",
}),
]
});
这允许我包含我的 .html
文件,如下所示:
<html>
<body>
<%= htmlWebpackPlugin.options.header %>
<p>Some text.</p>
<p>Some more text.</p>
<%= htmlWebpackPlugin.options.footer %>
</body>
</html>
乍一看它按预期工作,但是包含的 header.html
和 footer.html
文件在其初始状态下被“锁定”,如果我修改它们我仍然得到原始文件,而不是更新版本。我必须关闭 Webpack 开发服务器,然后重新运行它才能使更改生效。我猜测这是因为 fs.readFileSync()
仅在 Webpack 初始化时执行,而不是在检测到文件更改后执行。我该怎么做才能更新这些文件?
最佳答案
解决方案是将 fs.readFyleSync()
调用从 webpack.config 移至我的 index.html 文件中,因为配置文件仅在开发服务器启动时执行一次。
这是我的新 webpack.config:
// Get path to folder that contains HTML fragments
const folderPath = path.resolve(__dirname, "./src/static/");
module.exports = () => ({
// ... lots of Webpack boilerplate
plugins: [
//...
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: "./static/index.html",
filename: "index.html",
HTML_PATH: folderPath // <- Now I only pass the folder path
}),
]
});
...然后我在 HTML 中使用 readFileSync()
读取文件:
<html>
<body>
<%= require("fs").readFileSync(htmlWebpackPlugin.options.HTML_PATH + "/header.html") %>
<p>Some text.</p>
<p>Some more text.</p>
<%= require("fs").readFileSync(htmlWebpackPlugin.options.HTML_PATH + "/footer.html") %>
</body>
</html>
瞧!热重载 HTML 片段!
关于javascript - Webpack - 如何通过实时重新加载将 .html 片段包含到 index.html 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58868070/