Generating multiple HTML pages with HTMLWebpackPlugin
HTMLWebpackPlugin is a simple way to generate the html files for your web app. Using HTMLWebpackPlugin is covered in another post.
It is possible to generate multiple HTML files with HTMLWebpackPlugin and it is relatively simple. This will be based off the same project configuration as Using HTMLWebpackPlugin and Pug, and will be using pug.js - but it should work the same for however you are generating your HTML files.
The simplest way…
To generate multiple HTML files, you have to add multiple HTMLWepbackPlugins to your webpack plugins. Like so:
1 | /* webpack.config.js */ |
This works well when you only have a couple of files to generate, but is a bit awkward to maintain as you add more files. So is there a more elegant way to achieve this?
Yes, there is!!
We can achieve this in an easier to maintain way, and without adding much complexity to our build setup.
Project setup
The project setup will be almost identical to the Using HTMLWebpackPlugin and Pug post. The only difference will be the templates directory.
| Source files
1 | webpack.config.js |
As you can see the main difference is that our templates are all in a views
subfolder and everything else is in includes
. The important takeaway here, is that we want all the template files that correspond to our desired html files in a folder on their own.
Include templates function
To accomplish our task we will write a simple function to read the files from our views directory and generate an array of HTMLWebpackPlugins.
1 | function generateHtmlPlugins (templateDir) { |
Webpack config
With the generateHtmlPlugins function added our webpack configuration file will look like this:
1 | /* webpack.config.js */ |
And at the end there you should notice that we simply concatenate our htmlPlugins array to our webpackConfig.plugins array.
Multiple HTML files - done!
If we run webpack now, we will see that all our html files are generated (index, services, products and contact). Success!
And all that is required to add/generate more html files, is to create more template files in the views directory and name them correctly (‘products.pug’ becomes ‘products.html’).
A useful note: while in watch mode files added to the directory will not be picked up, but changes to template files included this way will be.