javascript - Webpack - 如何通过实时重新加载将 .html 片段包含到 index.html 中?

标签 javascript html webpack webpack-dev-server html-webpack-plugin

在 PHP 中,您可以包含文件片段以方便重用。在下面的示例中,我可以包含 header.phpfooter.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.htmlfooter.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/

相关文章:

javascript - 记录 Puppeteer Node.js 进程中客户端代码中进行的 `console` 调用

php - 如何使图像按钮运行 PHP 脚本?

javascript - 如何将事件附加到 Bootstrap 折叠面板的选择?

javascript - Elixir webpack 后 chrome 控制台中未定义的 var

css - 有没有办法用webpack动态加载css文件

javascript - 使用过滤器返回特定值

javascript - node.js - 如何使用 tls.connect 将 CA 添加到受信任的 CA 列表中

javascript - 不显眼的 JavaScript onload 函数

java - 如何使用 String.split() 根据 HTML 页面中的标签名称拆分字符串

css - 为什么 CSS 在我的 Angular2 开发服务器和生产版本上看起来不同?