5

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

索引.html

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

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

这不起作用:

_header.html

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

2 回答 2

4

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

索引.html

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

然后在_header.html

${require('html-loader?root=.!../partials/_nav.html')}
于 2018-05-09T19:43:31.660 回答
0

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').

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

于 2018-04-27T14:17:44.477 回答