Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Plugins and Assets

HTML Webpack Plugin

Use HtmlWebpackPlugin to generate HTML that includes your hashed bundles automatically: templates, title, chunks, multiple pages, minification, favicon and common mistakes.

Loaders transform individual files. Plugins do everything else: they hook into the build and can add files, change the output, define constants or report statistics. The most used plugin is HtmlWebpackPlugin, which solves a very practical problem. Once your bundle is named main.4be2f1a0.js, you cannot hard-code a script tag in index.html, because the name changes with every content change. The plugin writes an HTML file for you and inserts the correct <script> and <link> tags.

Terminal
npm install --save-dev html-webpack-plugin

The simplest setup

JavaScript
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: { filename: '[name].[contenthash:8].js', clean: true },
  plugins: [new HtmlWebpackPlugin({ title: 'My App' })],
};

After a build, dist/index.html looks like this:

HTML
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script defer src="main.4be2f1a0.js"></script>
  </head>
  <body></body>
</html>

The script is added to the <head> with defer by default (scriptLoading: 'defer'), so it runs after the document is parsed. If the page used CSS extracted with MiniCssExtractPlugin, matching <link rel="stylesheet"> tags are added too. All options are passed as an object to the constructor.

Node.js Stand-in: inject asset tags into HTML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Your own template

The default page is minimal. Almost every project supplies a template with a root element and metadata.

JavaScript
new HtmlWebpackPlugin({
  template: './src/index.html',
  filename: 'index.html',
  favicon: './src/favicon.ico',
  inject: 'head',
  templateParameters: { appName: 'Shop' },
})
HTML
<!-- src/index.html -->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><%= htmlWebpackPlugin.options.title %> - <%= appName %></title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

The default template engine is lodash-style (<%= value %>). htmlWebpackPlugin.options exposes the plugin options and htmlWebpackPlugin.files the generated files. Do not add your own <script> tag for the bundle: the plugin does it, and a duplicate would run the app twice.

Useful options:

Option What it does
template path to the template file
filename output name, can include a folder (pages/about.html)
inject 'head', 'body', true or false (no injection)
scriptLoading 'defer' (default), 'blocking', 'module'
chunks only include these entry names
excludeChunks leave these entries out
minify HTML minification (on in production by default)
favicon copy an icon and add a <link>
meta an object of <meta> tags

Multiple pages

Create one plugin instance per HTML file, and use chunks so each page only loads its own entry (Entry Points).

JavaScript
module.exports = {
  entry: { home: './src/home.js', about: './src/about.js' },
  plugins: [
    new HtmlWebpackPlugin({ template: './src/page.html', filename: 'index.html', chunks: ['home'] }),
    new HtmlWebpackPlugin({ template: './src/page.html', filename: 'about.html', chunks: ['about'] }),
  ],
};

Without chunks, every page would include every entry's script.

Node.js Stand-in: pick the chunks for each page

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Templates beyond lodash

The template option can point to a file processed by a loader: Pug, Handlebars, EJS or plain HTML with html-loader, which also resolves <img src> through Webpack (Asset Modules). Pick one rule per template extension:

JavaScript
{ test: /\.hbs$/, loader: 'handlebars-loader' }

For plain .html templates, remember that a rule matching .html would hijack the plugin's default template processing, so keep the rule for a different extension unless you want the loader involved.

Plugin hooks other plugins use

HtmlWebpackPlugin offers hooks of its own (via HtmlWebpackPlugin.getHooks(compilation)), such as alterAssetTags. Other plugins use them to add things like resource hints, CSP nonces or inlined runtime code. You will write a plugin of your own in Writing a Plugin.

Common mistakes

  • Blank page, no script tag. inject: false or the wrong chunks names.
  • App runs twice. A manual script tag next to the injected one.
  • Wrong asset URLs on a sub-path. Fix output.publicPath (Output and Filenames).
  • Old files in dist. Use output.clean: true.
  • Template changes ignored in dev. Restart the dev server if the template is outside the watch graph.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is HtmlWebpackPlugin useful with [contenthash] file names?

    Hashed names change over time, so the plugin generates the tags instead of you editing HTML.
  2. 2. Which option restricts a page to certain entries?

    chunks lists entry names to include; without it, all entries are included.
  3. 3. What is the default value of scriptLoading?

    Scripts get defer so they run after the HTML is parsed.
  4. 4. You added <script src="main.js"> to your template and the app runs twice. Why?

    The plugin already injects the bundle, so a manual tag duplicates it.

Summary

  • HtmlWebpackPlugin generates HTML and injects the right <script> and <link> tags for hashed bundles.
  • Provide a template; use <%= %> variables and do not add manual script tags.
  • Use one plugin instance per page with chunks for multi-page apps.
  • Key options: filename, inject, scriptLoading, minify, favicon, meta.
  • Pair it with output.clean and a correct publicPath.

Next: MiniCssExtractPlugin