【问题标题】:Webpack - How to include .html fragments into index.html with live reloading?Webpack - 如何通过实时重新加载将 .html 片段包含到 index.html 中?
【发布时间】:2020-03-11 01:52:45
【问题描述】:

在 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>

我已经通过使用html-webpack-plugin 成功地尝试了in this answer 方法,但是有一个问题。请参阅下面的配置:

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 初始化时执行,而不是在检测到文件更改后执行。我该怎么做才能更新这些文件?

【问题讨论】:

  • 如果你不习惯使用 webpack,我建议使用 express 和 pug 模板。每次请求 URL 时都会从磁盘读取模板,因此只需在浏览器中按 F5 即可看到更改。
  • @ChrisG 啊,谢谢你的建议,但这是一个有 4 个开发人员的现有项目,没有人喜欢进来改变整个框架的人 :) 我必须把它保存在 Webpack .

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


【解决方案1】:

解决方案是将 webpack.config 中的 fs.readFyleSync() 调用移动到我的 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 片段!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 2018-11-19
    • 2018-04-17
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多