有没有办法使用 html-webpack-plugin 包含部分内容?

新手上路,请多包涵

我正在使用 Webpack 编译我的脚本和 HTML(使用 html-webpack-plugin )。问题是,我有 5 个包含相同部分的 HTML 文件,我想将这些部分移动到单独的 .html 文件,然后 include 这些部分在每个 HTML 文件中。这样,如果我要更改这些较小的 HTML 文件,它将重新编译每个 HTML 文件以表示这些更改。

默认情况下,Webpack 会为 .js 文件执行此操作,但我可以对 HTML 文件使用类似的东西吗?

原文由 serge1peshcoff 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 430
2 个回答

您可以在模板中使用 <%= require('html!./partial.html') %> 。这里的例子: https ://github.com/jantimon/html-webpack-plugin/blob/master/examples/custom-template/template.html

原文由 display name 发布,翻译遵循 CC BY-SA 3.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-variables.js 看起来像这样:

 const hello = 'Hello!';
const bye = 'Bye!';

export {hello, bye}

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

原文由 pldg 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题