How can I configure Webpack HTML Plugin to only generate script tags, and not <html>, <body>, or <head> tags?
You can configure html-webpack-plugin to build the file based on a custom template. If the template does not have a <body> tag, the script includes are simply appended to the end of the file. There are more advanced configuration options available as described in the project documentation, but for your purpose all you need is to create an empty file named e.g. includes.html, and then specify it as the template in webpack.config.js:
module.exports = {
...
plugins: [
new HtmlWebpackPlugin({
template: 'includes.html'
})
]
...
}
If a completely empty file does not work, just add a newline or a html comment.
An empty template alone will still result in <head></head> tags being generated. As far as I can tell, the doc page says nothing about removing it, so postprocessing may be required.*
First, you actually don't even need to create a file if you pass an empty string to templateContent.
Second, to postprocess, you can use the beforeEmit hook. (See flowchart here.) Just define a new plugin. This plugin is based on the one from the GitHub page, but you don't actually need a separate plugin file.
So the webpack.config.js looks something like this:
// Define plugin
class ScriptExtractor {
apply(compiler) {
compiler.hooks.compilation.tap('ScriptExtractor', (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
'Remove head',
(data, cb) => {
// Remove the unwanted strings
data.html = data.html.replace(/^<head>|<\/head>$/g, '');
cb(null, data);
}
);
});
}
}
module.exports = {
plugins: [
// Use plugin
new ScriptExtractor,
new HtmlWebpackPlugin({
// Use empty template
templateContent: ''
})
]
};
* There is a nice, short workaround/hack if you're just generating <script> tags and nothing else. As s6mike discovered, you can use the empty templateContent and inject: 'body' (the other values for inject do not work):
module.exports = {
plugins: [
new HtmlWebpackPlugin({
inject: 'body',
templateContent: ''
})
]
};
However, if you are using base: to alter the base URL, HtmlWebpackPlugin will once again generate <head> tags. I think this is because <base> can only go in the <head>, and you're now specifying that you want the scripts in the <body>. The same may go for the meta: property.
Output with <base>: <head><base href="..."></head><script...>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With