html-webpack-plugin

repository·main·Indexed 27 days ago

https://github.com/jantimon/html-webpack-plugin

A Webpack plugin that simplifies the creation of HTML files to serve bundles by automatically injecting script and link tags for assets. It supports custom templates via lodash, inline content through templateContent, and provides options for minification, cache busting, meta tags, and chunk selection. Compatible with Webpack 4 and 5.

Tokens
7.1K
Snippets
23
Records
42
Agent score
95%

What's inside html-webpack-plugin

  1. Overview of html-webpack-plugin

    main
    The html-webpack-plugin simplifies the creation of HTML files to serve your Webpack bundles. It is particularly useful when bundle filenames include hashes that change with every compilation. You can let the plugin generate an HTML file automatically, provide your own template using lodash templates, or use your own loader.
  2. Migrate from 1.x to 2.x: Automatic Asset Injection

    main

    In version 2.x, the inject option defaults to true. This means all JavaScript, CSS, and manifest files are automatically injected into your HTML. You no longer need to manually add <script> or <link> tags for your bundles in your custom templates.

    To use the default behavior, simply instantiate the plugin without arguments:

    var HtmlWebpackPlugin = require("html-webpack-plugin");
    
    module.exports = {
      // ...
      plugins: [new HtmlWebpackPlugin()],
    };
  3. Use Loaders inside HTML templates

    main

    In 2.x, you can use Webpack loaders directly inside your HTML templates using require(). This is useful for including partials or processing assets like images.

    Example template usage:

    <link
      rel="apple-touch-icon"
      href="<%- require('../images/favicons/apple-icon-60x60.png') %>"
    />
    <%= require('partial.html') %>

    Required Webpack Configuration: To use this, you must configure html-loader and an asset loader (like asset/resource). Note that you should exclude your main template from the html-loader to prevent it from being parsed by the loader instead of the plugin's own templating engine.

    module: {
      rules: [
        { test: /\.png$/, type: "asset/resource" },
        {
          test: /\.html$/,
          exclude: /index\.html$/, // exclude your base template
          loader: "html",
        },
      ];
    }
  4. Install html-webpack-plugin

    main

    Install the plugin depending on your Webpack version. For Webpack 5, use the latest version. For Webpack 4, install version 4 specifically.

    # Webpack 5
    npm i --save-dev html-webpack-plugin
    # or
    yarn add --dev html-webpack-plugin
    
    # Webpack 4
    npm i --save-dev html-webpack-plugin@4
    # or
    yarn add --dev html-webpack-plugin@4
  5. Set a loader directly for the template

    main

    You can specify a loader directly within the template option string using Webpack's inline loader syntax. This is useful for quickly applying a specific loader to your template file.

    new HtmlWebpackPlugin({
      // For details on `!!` see https://webpack.js.org/concepts/loaders/#inline
      template: "!!handlebars-loader!src/index.hbs",
    });
  6. Configure Custom Template Engines (e.g., Pug)

    main

    You can use different template engines by specifying the loader in the template option or by configuring Webpack rules for specific file extensions.

    Option 1: Inline loader specification Use the loader!template syntax. Note: Do not use this if you already have a global rule for that file type, as Webpack may attempt to apply the loader twice.

    new HtmlWebpackPlugin({
      template: "pug-loader!template.pug",
    })

    Option 2: Webpack rules (Recommended) Configure Webpack to handle the file extension globally, then simply point the plugin to the file.

    module.exports = {
      module: {
        rules: [{ test: /\.pug$/, loader: "pug-loader" }],
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: "template.pug",
        }),
      ],
    };
  7. Migrate from 1.x to 2.x: Update Templating Syntax

    main

    Version 2.x replaced blueimp with lodash/underscore/ejs templates. This change introduces two key syntax updates:

    1. Remove the o prefix: Template variables no longer use the o. prefix. For example, <%= o.htmlWebpackPlugin.options.environment %> must be changed to <%= htmlWebpackPlugin.options.environment %>.
    2. Escaping variables: To prevent unexpected behavior by escaping variables, use <%- instead of <%=.

    Example transition:

    • Old (1.x): <body class="{%= o.htmlWebpackPlugin.options.environment %}">
    • New (2.x): <body class="<%= htmlWebpackPlugin.options.environment %>"> (unescaped) or <body class="<%- htmlWebpackPlugin.options.environment %>"> (escaped).
  8. Generate multiple HTML files

    main

    To generate more than one HTML file in your build, declare the HtmlWebpackPlugin multiple times within your webpack plugins array. Each instance can have its own filename and template.

    {
      entry: 'index.js',
      output: {
        path: __dirname + '/dist',
        filename: 'index_bundle.js'
      },
      plugins: [
        new HtmlWebpackPlugin(), // Generates default index.html
        new HtmlWebpackPlugin({  // Also generate a test.html
          filename: 'test.html',
          template: 'src/assets/test.html'
        })
      ]
    }
  9. Use contenthash for long term caching

    main

    To implement long term caching for your HTML files, use the [contenthash] template string in the filename option. This ensures the filename changes only when the content changes.

    new HtmlWebpackPlugin({
      filename: "index.[contenthash].html",
    });
  10. Set a loader using module.rules for templates

    main

    You can define how templates are processed by adding a rule to your Webpack module.rules configuration. This allows you to associate specific file extensions (like .hbs) with a specific loader.

    {
      module: {
        rules: [
          {
            test: /\.hbs$/,
            loader: 'handlebars-loader'
          },
        ]
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: 'src/index.hbs'
        })
      ]
    }
  11. Use custom HTML templates

    main

    You can supply your own template using the template option. The plugin will automatically inject necessary CSS, JS, manifest, and favicon files into the markup. By default, it uses lodash syntax for templating. If you have a specific loader (like handlebars-loader), you can use it by specifying the appropriate file extension in the template option.

    // Using a custom HTML file
    new HtmlWebpackPlugin({
      title: "Custom template",
      template: "index.html",
    });
    
    // Using a Handlebars template with a loader configured
    new HtmlWebpackPlugin({
      title: 'Custom template using Handlebars',
      template: 'index.hbs'
    });
  12. Implement the beforeEmit callback

    main
    When implementing a callback for the beforeEmit event, you must ensure the callback receives HtmlWebpackPluginData as an argument. This allows the data to be passed correctly to other plugins listening on the same beforeEmit event.