【问题标题】:HTML Partials with Webpack带有 Webpack 的 HTML 部分
【发布时间】:2020-11-27 13:07:44
【问题描述】:

我有一个相当长的 HTML 文件。我想将其拆分为一个基本文件和多个较小的文件,然后我可以将它们包含到所述基本文件中。我正在使用 Webpack,所以我认为必须有一种方法可以在构建时执行此操作。

我环顾四周,尝试了ejs-easy-loader,但无法正常工作。我不确定最好的方法是什么,或者是否有更好的选择。

从概念上讲,我想这样做:

项目结构

index.html
partials
- partial-1.html
- partial-2.html
- ...
- partial-9.html

index.html

<html>
<body>

Base file content

<!-- Include partial-1.html -->
<!-- Include partial-2.html -->
<!-- ... -->
<!-- Include partial-9.html -->

More base file content

</body>
</html>

【问题讨论】:

    标签: webpack ejs webpack-dev-server partials


    【解决方案1】:

    尝试将 html-loader 添加为 devDependency

    然后(假设 webpack 5)

    <body>
    
    Base file content
    
    <!-- Include partial-1.html -->
    <%= require('html-loader!./partials/partial1.html').default %>
    
    <!-- Include partial-2.html -->
    <!-- ... -->
    <!-- Include partial-9.html -->
    
    More base file content
    
    </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      我认为最好的方法是在 webpack 构建过程中解决它,这意味着挂钩到编译器并从你的部分构建 main.html。

      您可以创建一个简单的插件来执行此操作:

      const fs = require("fs");
      
      class BuildHtml {
          constructor(partialHtmls) {
              this.partialHtmls = partialHtmls;
          }
          apply(compiler) {
              // Called before emitting assets to dist folder.
              compiler.hooks.emit.tap('BuildHtml', (compilation) => {
                  // Construct main html content from partial htmls.
                  let mainHtmlContent = "<html><body>" + this.partialHtmls.join("") + "</body></html>"
      
                  // '/dist/index.html' - should be the index.html output path if you use HtmlWebpackPlugin.
                  fs.writeFileSync('/dist/index.html', mainHtmlContent);
      
                  return true;
              });
          }
      }
      

      并在 webpack 配置中使用你的插件:

      plugins: [
          BuildHtml
      ]
      

      【讨论】:

        猜你喜欢
        • 2018-05-26
        • 2017-11-29
        • 1970-01-01
        • 2018-08-22
        • 1970-01-01
        • 1970-01-01
        • 2018-08-16
        • 1970-01-01
        • 2023-03-13
        相关资源
        最近更新 更多