我正在使用Webpack来编译我的脚本和HTML语言(使用html-webpack-plugin)。问题是,我有5个包含相同部分的超文本标记语言文件,我想将这些部分移动到单独的.html文件中,然后在每个超文本标记语言文件中include这些部分。这样,如果我要更改这些较小的HTML文件,它将重新编译每个HTML文件以表示这些更改。
默认情况下,Webpack会对.js文件执行此操作,但我可以对HTML文件使用类似的操作吗?
发布于 2017-02-13 17:25:20
您可以在模板中使用<%= require('html!./partial.html') %>。示例如下:https://github.com/jantimon/html-webpack-plugin/blob/master/examples/custom-template/template.html
发布于 2018-03-12 02:52:31
另一个略有不同的解决方案。
使用带有interpolate选项的html-loader。
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 %>中写入标题或使用单独的javascript文件来处理变量即可。
发布于 2018-07-10 11:19:32
请查看Partials for HTML Webpack Plugin,以获得更优雅的内容。它允许您设置HTML文件并包含它们,类似于您要查找的内容,如下所示:
plugins: [
new HtmlWebpackPlugin(),
new HtmlWebpackPartialsPlugin({
path: './path/to/partials/body.html'
})
]还可以配置它的添加位置,例如head vs body,opening vs closing,并允许您传递变量。
https://stackoverflow.com/questions/42193689
复制相似问题