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

问题描述 投票:1回答:1

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

javascript html webpack webpack-dev-server html-webpack-plugin
1个回答
0
投票

解决方案是将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>

Voilá!热重载HTML片段!

© www.soinside.com 2019 - 2024. All rights reserved.