HTML Webpack Plugin allows for the creation of an HTML file when bundling your code so that you have an HTML file that your JavaScript code will be injected into and also load the bundled JavaScript file created by Webpack.
Installing the plugin
In order to install the plugin, make sure you have either npm or yarn installed. At the command prompt type the following:
If you have Webpack 5
npm install --save-dev html-webpack-plugin@next
OR
yarn add --dev html-webpack-plugin@next
If you have Webpack 4
npm install --save-dev html-webpack-plugin
OR
yarn add --dev html-webpack-plugin
Initialize the plugin in your Webpack configuration file
In your Webpack configuration file, (it’s usually either webpack.config.js
or webpack.config.ts
depending on if your are using JavaScript or Typescript), add the following code in the plugins
section:
plugins: [
new HtmlWebpackPlugin({
title: 'My Web App',
filename: 'index.html',
template: 'template.html',
inject: true
}),
///....
]
title:
Sets the title of the newly created HTML file, which is injected in between the (<title>...</title>
) tags.
filename:
The filename of the HTML file that will be created.
template:
The filename of an HTML file you want the plugin to use as a model when creating the HTML for your bundle. This is optional. In my case, I used it because I wanted to add a div with an id of root
for a React project. If you end up using a template file, make sure to put in between the <title></title>
tags the following code: <%= htmlWebpackPlugin.options.title %>
. This retrieves the value you set for the title
parameter above.
inject:
This parameter injects the JavaScript filename that Webpack creates when it bundles your code into the newly created HTML file in between the <script></script>
tags.
Once you have finished configuring the plugin, save the Webpack config file and run Webpack to create the HTML file and bundle your code:
Development mode
npm run webpack --config nameOfWebpackConfigFile.js --mode=development
OR
yarn run webpack --config nameOfWebpackConfigFile.js --mode=development
Production mode
npm run webpack --config nameOfWebpackConfigFile.js --mode=production
OR
yarn run webpack --config nameOfWebpackConfigFile.js --mode=production