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

ser*_*off 26 html frontend webpack

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

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

小智 29

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

  • 如何为每个部分添加模板特定变量? (6认同)
  • 您可以尝试使用 - https://github.com/Vishal0203/file-include-webpack-plugin 这与 `gulp-file-include` 类似 (2认同)
  • 有关此问题的一些小注释-使用Webpack 4时,您将得到一个错误:** BREAKING CHANGE:使用装载程序时,不再允许省略'-loader'后缀。**-因此,内联要求必须为`&lt;% = require('html-loader!./ partial.html')%&gt;` (2认同)
  • @klewis `npm install --save-dev html-loader` 就可以了。不要将加载器添加到 webpack 配置中,否则会干扰 `html-webpack-plugin`。 (2认同)

pld*_*ldg 11

另一个略有不同的解

使用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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在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>
Run Code Online (Sandbox Code Playgroud)

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

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

export {hello, bye}
Run Code Online (Sandbox Code Playgroud)

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

  • `interpolate` 被删除,文档没有等效的示例:https://github.com/webpack-contrib/html-loader/blob/7aa1e4abe23426a9bd14a22fae632a695598bdba/CHANGELOG.md#100-2020-03-19 (7认同)