The HtmlWebpackPlugin will allow Webpack to process HTML files that contain JavaScript, for instance. To start working with it, we need to install it using the command line, and then set the configuration correctly, as follows:
- First, install the plugin using the command-line utility, and then adjust the webpack.config.js file, as follows:
npm install --save-dev html-webpack-plugin
The preceding code block shows the installation of the HtmlWebpackPlugin for use in our project.
- Next, we have to incorporate the plugin into our configuration. Let's take a look at the webpack.config.js file when associated with this plugin, as follows:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './src/index.js', print: './src/print.js' }, plugins: [ new HtmlWebpackPlugin({ title: 'Output Management' }) ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };
Note the use of the require expression and the plugins: option key, both of which serve to permit the use of the plugin.
Before a build is run, note that the HtmlWebpackPlugin will generate its index.html file by default, even though there already is one in the dist/ folder. As a result, the existing file will be overwritten.
- Now, run the build using your command-line utility. Once this is done, you will see the following result in the command-line utility window, indicating a successful bundling:
... Asset Size Chunks Chunk Names print.bundle.js 544 kB 0 [emitted] [big] print app.bundle.js 2.81 kB 1 [emitted] app index.html 249 bytes [emitted] ...
Opening the index.html file in your code editor or Notepad will reveal that the plugin has created a new file, and all the bundles are automatically added.
That concludes our tutorial of Webpack's HtmlWebpackPlugin. In the following subsection, we will again embark on some tidying up in your project directory.