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

Is there a way to include partial using html-webpack-plugin?

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

Webpack 默认为 .js 文件做这个,但我可以对 HTML 文件使用类似的东西吗?

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

另一种略有不同的解决方案。

使用 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 文件来处理变量。

查看 Partials for HTML Webpack Plugin 以获得更优雅的内容。它允许您设置 HTML 文件并包含类似于您正在寻找的文件:

plugins: [
  new HtmlWebpackPlugin(),
  new HtmlWebpackPartialsPlugin({
    path: './path/to/partials/body.html'
  })
]

还可以配置它的添加位置,例如头部与 body、打开与关闭,并允许您传入变量。