【问题标题】:Webpack: include html partial inside another partial?Webpack:在另一个部分中包含html部分?
【发布时间】:2018-08-16 13:03:50
【问题描述】:

有没有办法使用 webpack 将 html 部分包含在另一个部分中? 我正在使用 html-loader 来执行此操作:

index.html

<%= require('html-loader!./partials/_header.html') %>

但是当我尝试在 _header.html 中包含另一个部分时,它无法呈现它。

这不起作用:

_header.html

<%= require('html-loader!./partials/_nav.html') %>

【问题讨论】:

    标签: webpack partial html-webpack-plugin webpack-html-loader


    【解决方案1】:

    我结合了一点,我能够找到解决方案。

    index.html

    <%= require('html-loader?root=.&minimize=true&interpolate!./partials/_header.html') %>
    

    然后在 _header.html

    ${require('html-loader?root=.!../partials/_nav.html')}
    

    【讨论】:

      【解决方案2】:

      html-loaderinterpolate 选项一起使用。

      https://github.com/webpack-contrib/html-loader#interpolation

      { test: /\.(html)$/,
        include: path.join(__dirname, 'src/views'),
        use: {
          loader: 'html-loader',
          options: {
            interpolate: true
          }
        }
      }
      

      然后在 html 页面中你可以导入部分 html 和 javascript 变量。

      <!-- Importing top <head> section -->
      ${require('./partials/top.html')}
      <title>Home</title>
      </head>
      <body>
        <!-- Importing navbar -->
        ${require('./partials/nav.html')}
        <!-- Importing variable from javascript file -->
        <h1>${require('../js/html-variables.js').hello}</h1>
        <!-- Importing footer -->
        ${require('./partials/footer.html')}
      </body>
      </html>
      

      html-variables.js 看起来像这样:

      const hello = 'Hello!';
      const bye = 'Bye!';
      
      export {hello, bye}
      

      您还可以使用 ${require('path/to/your/partial.html') 以同样的方式在另一个部分中包含部分。

      唯一的缺点是你不能像&lt;%= htmlWebpackPlugin.options.title %&gt;这样从HtmlWebpackPlugin导入其他变量(至少我找不到导入它们的方法),只需在你的html中写下标题或使用单独的如果需要,用于处理变量的 javascript 文件。

      【讨论】:

      • 你知道我不喜欢什么,当在多页面应用程序中使用这种方法时:你必须重复自己。在每个页面中,您必须要求顶部、导航和页脚。而不是一个包含所有内容的布局页面,您只需导入正文和此页面所需的所有其他内容。
      • @Legends 我不再使用 html-loader,有更好的方法来处理这个问题。比如我做了这个static site generator with webpack(我也有更新版本,有时间我会上传)
      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 2014-10-16
      • 2014-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      相关资源
      最近更新 更多