In this Webpack 5 video tutorial, I’m going to show you how to generate HTML files to serve your Webpack bundles automatically, and this is especially useful if Webpack bundles include a hash in the filename, which will change on every compilation, which makes the browser to get the latest version of the file from the server instead of using a cached one whenever it has a new hash. Webpack will do this for us with the help of the html-webpack-plugin.
Install Html Webpack Plugin
First, I’m going to navigate to my project directory. I’m then going to install the html-webpack-plugin into our dev dependencies. So I will type npm install --save-dev html-webpack-plugin
.
Configure Webpack 5 to use html-webpack-plugin
Once html-webpack-plugin is installed, we can go back to our Webpack config, and we need to make some adjustments.
The first thing that we are going to do is import the html-webpack-plugin. Then we will add another node called “plugins”, and this should take in an array. I’m then going to use new HtmlWebpackPlugin()
.
To make some customization in the generated HTML file, we need to make some adjustments in the html-webpack-plugin configuration options.
To set the HTML document title, we will need to assign the “title” property with what we want to put in our HTML file title tag.
You can also specify the HTML filename by setting the “filename” property if you want to use a filename other than index.html.
We can choose where we want to put all of the JavaScript resources by setting the “inject” property to body or head. If you set it to the body, script tags will be generated at the bottom of the body tag.
Suppose you have chosen to put the JavaScript resources in the head. In that case, you could set the “scriptLoading” property to “defer” to improve the page startup performance.
Now I’m going to move index.html from dist to the src folder. Then we will delete everything from the dist folder, so we can automatically generate the index.html that links to the Webpack bundle.
Let’s go back to the terminal. And I’m going to type npm run build
, which will generate two files for me, index.html and bundle.js.
Let’s take a look at that folder, and this is what the html-webpack-plugin generated for us.
Use a Custom Template with html-webpack-plugin
We will need to assign the “template” property with the template file path to use a custom template. I will use ./src/index.html
.
Let’s get rid of the title property cause we already set the title directly in the Html template.
Since we are using index.html as a template, we do not need script tag in it anymore cause the html-webpack-plugin will create it.
Let’s go back over the terminal. And I’m going to type npm run build
again, and it will generate the index.html using the template.
GitHub Repo
Check the GitHub repository here → GitHub