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

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

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

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

本文链接:https://www.f2er.com/3098737.html

大家都在问