簡體   English   中英

Webpack - 如何包含。html 片段進入索引。html 實時重新加載?

[英]Webpack - How to include .html fragments into index.html with live reloading?

在 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成功嘗試了這個答案中的方法,但是有一個問題。 請參閱下面的配置:

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>

It works as expected at first glance, but the included header.html and footer.html files get "locked" in their initial state, and if I modify them I still get the original files, not the updated version. 我必須關閉 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碎片!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM