将html-loader 与interpolate 选项一起使用。
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>
html-variables.js 看起来像这样:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello, bye}
您还可以使用 ${require('path/to/your/partial.html') 以同样的方式在另一个部分中包含部分。
唯一的缺点是你不能像<%= htmlWebpackPlugin.options.title %>这样从HtmlWebpackPlugin导入其他变量(至少我找不到导入它们的方法),只需在你的html中写下标题或使用单独的如果需要,用于处理变量的 javascript 文件。