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

时间:2017-02-12 21:51:04

标签: html webpack frontend

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

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

3 个答案:

答案 0 :(得分:22)

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

答案 1 :(得分:7)

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

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 %>导入其他变量(至少我找不到导入它们的方法)但是对我来说它和&#0}} #39;不是问题,只需在你的html中写标题或使用单独的javascript文件来处理变量。

答案 2 :(得分:1)

查看Partials for HTML Webpack Plugin,以获得更优雅的体验。它使您可以设置HTML文件,并包含与所需内容类似的文件,

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

还可以对其添加位置进行配置,例如头部与身体,打开与关闭,并允许您传入变量。