Reputation: 4660
I am using Webpack to compile my scripts and HTML (using html-webpack-plugin
). The thing is, I have 5 HTML files that contains the same parts and I want to move these parts to separate .html
files and then include
these parts in every HTML file. This way, if I will change these smaller HTML files, it will recompile every HTML file to represent these changes.
Webpack does this for .js files by default, but can I use something like that for HTML files?
Upvotes: 47
Views: 38452
Reputation: 7561
You can use html-loader
and posthtml
. Then you can use the posthtml-include
plugin.
const postHtml = require('posthtml');
const postHtmlInclude = require('posthtml-include');
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
esModule: false,
preprocessor: async (content, loaderContext) => {
try {
return await postHtml(postHtmlInclude()).process(content)).html;
} catch (error) {
loaderContext.emitError(error);
return content;
}
},
},
},
},
Upvotes: 0
Reputation: 145
Check out Partials for HTML Webpack Plugin for something a little more elegant. It lets you set up HTML files and include them similar to what you're looking for simply like:
plugins: [
new HtmlWebpackPlugin(),
new HtmlWebpackPartialsPlugin({
path: './path/to/partials/body.html'
})
]
Also configurable for where it gets added such as head vs body, opening vs closing, and lets you pass in variables.
Upvotes: 2
Reputation: 2588
Another slightly different solution.
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-variables.js
looks like this:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello, bye}
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) but for me it's not an issue, just write the title in your html or use a separate javascript file for handle variables.
Upvotes: 19
Reputation: 673
You can use <%= require('html!./partial.html') %>
in your template. Example here: https://github.com/jantimon/html-webpack-plugin/blob/master/examples/custom-template/template.html
Upvotes: 51