Using html-loader
with interpolate
option.
https://github.com/webpack-contrib/html-loader#interpolation
{ test: /\.(html)$/,
include: path.join(__dirname, 'src/views'),
use: {
loader: 'html-loader',
options: {
interpolate: true
}
}
}
And then in html pages you can import partials html and javascript variables.
<!-- 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
looks like this:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello, bye}
You can also include partials inside another partial the same way, using ${require('path/to/your/partial.html')
.
The only downside is that you can't import other variables from HtmlWebpackPlugin
like this <%= htmlWebpackPlugin.options.title %>
(at least I can't find a way to import them), just write the title in your html or use a separate javascript file for handle variables if needed.