Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

vuepress-html-webpack-plugin

jantimon312.5kMIT3.2.0

Simplifies creation of HTML files to serve your webpack bundles

webpack, plugin, html, html-webpack-plugin

readme

Fork

This is published as vuepress-html-webpack-plugin to be used in VuePress. This is to fix a situation when the user installs a version of html-webpack-plugin that is compatible with VuePress' (which causes it to be hoisted to node_modules root) but also with a version of webpack that is incompatible. Because html-webpack-plugin directly make requires into webpack internals, it ends up requiring the internal modules from the incompatible version of webpack.

npm node npm deps tests Backers on Open Collective Sponsors on Open Collective

HTML Webpack Plugin

Plugin that simplifies creation of HTML files to serve your bundles

Install

  npm i --save-dev html-webpack-plugin
  yarn add --dev html-webpack-plugin

This is a webpack plugin that simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.

Plugins

The html-webpack-plugin provides hooks to extend it to your needs. There are already some really powerful plugins which can be integrated with zero configuration

Usage

The plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags. Just add the plugin to your webpack config as follows:

webpack.config.js

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

module.exports = {
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin()
  ]
}

This will generate a file dist/index.html containing the following

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
    <script src="index_bundle.js"></script>
  </body>
</html>

If you have multiple webpack entry points, they will all be included with script tags in the generated HTML.

If you have any CSS assets in webpack's output (for example, CSS extracted with the ExtractTextPlugin) then these will be included with <link> tags in the HTML head.

If you have plugins that make use of it, html-webpack-plugin should be ordered first before any of the integrated plugins.

Options

You can pass a hash of configuration options to html-webpack-plugin. Allowed values are as follows

Name Type Default Description
title {String} The title to use for the generated HTML document
filename {String} 'index.html' The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: assets/admin.html)
template {String} webpack require path to the template. Please see the docs for details
templateParameters {Boolean|Object|Function} Allows to overwrite the parameters used in the template
inject {Boolean|String} true true || 'head' || 'body' || false Inject all assets into the given template or templateContent. When passing true or 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element
favicon {String} Adds the given favicon path to the output HTML
meta {Object} {} Allows to inject meta-tags. E.g. meta: {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}
minify {Boolean|Object} true Pass html-minifier's options as object to minify the output
hash {Boolean} false If true then append a unique webpack compilation hash to all included scripts and CSS files. This is useful for cache busting
cache {Boolean} true Emit the file only if it was changed
showErrors {Boolean} true Errors details will be written into the HTML page
chunks {?} ? Allows you to add only some chunks (e.g only the unit-test chunk)
chunksSortMode {String|Function} auto Allows to control how chunks should be sorted before they are included to the HTML. Allowed values are 'none' | 'auto' | 'dependency' | 'manual' | {Function}
excludeChunks {Array.<string>} Allows you to skip some chunks (e.g don't add the unit-test chunk)
xhtml {Boolean} false If true render the link tags as self-closing (XHTML compliant)

Here's an example webpack config illustrating how to use these options

webpack.config.js

{
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'My App',
      filename: 'assets/admin.html'
    })
  ]
}

Generating Multiple HTML Files

To generate more than one HTML file, declare the plugin more than once in your plugins array

webpack.config.js

{
  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'
    })
  ]
}

Writing Your Own Templates

If the default generated HTML doesn't meet your needs you can supply your own template. The easiest way is to use the template option and pass a custom HTML file. The html-webpack-plugin will automatically inject all necessary CSS, JS, manifest and favicon files into the markup.

plugins: [
  new HtmlWebpackPlugin({
    title: 'Custom template',
    // Load a custom template (lodash by default see the FAQ for details)
    template: 'index.html'
  })
]

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
  </body>
</html>

If you already have a template loader, you can use it to parse the template. Please note that this will also happen if you specifiy the html-loader and use .html file as template.

webpack.config.js

module: {
  loaders: [
    { test: /\.hbs$/, loader: "handlebars" }
  ]
},
plugins: [
  new HtmlWebpackPlugin({
    title: 'Custom template using Handlebars',
    template: 'index.hbs'
  })
]

You can use the lodash syntax out of the box. If the inject feature doesn't fit your needs and you want full control over the asset placement use the default template of the html-webpack-template project as a starting point for writing your own.

The following variables are available in the template:

  • htmlWebpackPlugin: data specific to this plugin

    • htmlWebpackPlugin.files: a massaged representation of the assetsByChunkName attribute of webpack's stats object. It contains a mapping from entry point name to the bundle filename, eg:

      "htmlWebpackPlugin": {
        "files": {
          "css": [ "main.css" ],
          "js": [ "assets/head_bundle.js", "assets/main_bundle.js"],
          "chunks": {
            "head": {
              "entry": "assets/head_bundle.js",
              "css": [ "main.css" ]
            },
            "main": {
              "entry": "assets/main_bundle.js",
              "css": []
            },
          }
        }
      }

      If you've set a publicPath in your webpack config this will be reflected correctly in this assets hash.

    • htmlWebpackPlugin.options: the options hash that was passed to the plugin. In addition to the options actually used by this plugin, you can use this hash to pass arbitrary data through to your template.

  • webpack: the webpack stats object. Note that this is the stats object as it was at the time the HTML template was emitted and as such may not have the full set of stats that are available after the webpack run is complete.

  • webpackConfig: the webpack configuration that was used for this compilation. This can be used, for example, to get the publicPath (webpackConfig.output.publicPath).

  • compilation: the webpack compilation object. This can be used, for example, to get the contents of processed assets and inline them directly in the page, through compilation.assets[...].source() (see the inline template example).

Filtering Chunks

To include only certain chunks you can limit the chunks being used

webpack.config.js

plugins: [
  new HtmlWebpackPlugin({
    chunks: ['app']
  })
]

It is also possible to exclude certain chunks by setting the excludeChunks option

webpack.config.js

plugins: [
  new HtmlWebpackPlugin({
    excludeChunks: [ 'dev-helper' ]
  })
]

Events

To allow other plugins to alter the HTML this plugin executes the following events:

Sync

  • html-webpack-plugin-alter-chunks

Async

  • html-webpack-plugin-before-html-generation
  • html-webpack-plugin-before-html-processing
  • html-webpack-plugin-alter-asset-tags
  • html-webpack-plugin-after-html-processing
  • html-webpack-plugin-after-emit

Example implementation: html-webpack-harddisk-plugin

plugin.js

function MyPlugin(options) {
  // Configure your plugin with options...
}

MyPlugin.prototype.apply = function (compiler) {
  compiler.plugin('compilation', (compilation) => {
    console.log('The compiler is starting a new compilation...');

    compilation.plugin(
      'html-webpack-plugin-before-html-processing',
      (data, cb) => {
        data.html += 'The Magic Footer'

        cb(null, data)
      }
    )
  })
}

module.exports = MyPlugin

webpack.config.js

plugins: [
  new MyPlugin({ options: '' })
]

Note that the callback must be passed the HtmlWebpackPluginData in order to pass this onto any other plugins listening on the same html-webpack-plugin-before-html-processing event

Maintainers


Jan Nicklas

Thomas Sileghem

Contributors

This project exists thanks to all the people who contribute.

You're free to contribute to this project by submitting issues and/or pull requests. This project is test-driven, so keep in mind that every change and new feature should be covered by tests.

This project uses the semistandard code style.

Backers

Thank you to all our backers! 🙏 Become a backer

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Become a sponsor

changelog

Change Log

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

3.2.0 (2018-04-03)

Bug Fixes

  • loader: Allow to add new template parameters (f7eac19), closes #915
  • loader: Use lodash inside the loader directly (7b4eb7f), closes #786

Features

3.1.0 (2018-03-22)

Features

  • Allow to overwrite the templateParameter #830 (c5e32d3)

3.0.8 (2018-03-22)

Bug Fixes

  • compiler: Fallback to 3.0.7 because of #900 (05ee29b)

3.0.7 (2018-03-19)

Bug Fixes

3.0.6 (2018-03-06)

Bug Fixes

3.0.5 (2018-03-06)

Bug Fixes

  • entries: do not ignore JS if there is also CSS (020b714)
  • entries: Don't add css entries twice (0348d6b)
  • hooks: Remove deprecated tapable calls #879 (2288f20)

3.0.4 (2018-03-01)

Bug Fixes

  • entries: Don't add css entries twice (e890f23)

3.0.3 (2018-03-01)

Refactor

  • performance: Reduce the amount of chunk information gathered based on #825 (06c59a7)

3.0.2 (2018-03-01)

Bug Fixes

  • query-loader: In case no query is provided, return an empty object. This fixes #727 (7587754)

3.0.1 (2018-03-01)

Bug Fixes

  • package: Remove the extract-text-webpack-plugin peer dependency (57411a9)

3.0.0 (2018-28-02)

Features

  • Add support for the new webpack tapable to be compatible with webpack 4.x
  • Remove bluebird dependency

BREAKING CHANGES

  • Similar to webpack 4.x the support for node versions older than 6 are no longer supported

2.30.1

  • Revert part the performance optimization (#723) because of #753.

2.30.0

  • Add manual sort
  • Performance improvements (#723)

2.29.0

  • Add support for Webpack 3

2.28.0

  • Backport 3.x void tag for plugin authors

2.27.1

  • Revert 2.25.0 loader resolving

2.27.0

  • Fix a chunksorter webpack 2 issue (#569)
  • Fix template path resolving (#542)

2.26.0

  • Allow plugins to add attributes without values to the <script> and <link> tags

2.25.0

  • Clearer loader output
  • Add basic support for webpack 2

2.24.1

  • Hide event deprecated warning of 'applyPluginsAsyncWaterfall' for html-webpack-plugin-after-emit and improve the warning message.

2.24.0

  • Update dependencies
  • Add deprecate warning for plugins not returning a result
  • Add [path] for favicons

2.23.0

  • Update dependencies
  • Stop automated tests for webpack 2 beta because of #401

2.22.0

  • Update dependencies

2.21.1

  • Better error handling (#354)

2.21.0

  • Add html-webpack-plugin-alter-asset-tags event to allow plugins to adjust the script/link tags

2.20.0

  • Exclude chunks works now even if combined with dependency sort

2.19.0

  • Add html-webpack-plugin-alter-chunks event for custom chunk sorting and interpolation

2.18.0

  • Updated all dependencies

2.17.0

  • Add type attribute to script element to prevent issues in Safari 9.1.1

2.16.2

  • Fix bug introduced by 2.16.2. Fixes #315

2.16.1

  • Fix hot module replacement for webpack 2.x

2.16.0

  • Add support for dynamic filenames like index[hash].html

2.15.0

  • Add full unit test coverage for the webpack 2 beta version
  • For webpack 2 the default sort will be 'dependency' instead of 'id'
  • Upgrade dependencies

2.14.0

  • Export publicPath to the template
  • Add example for inlining css and js

2.13.0

  • Add support for absolute output file names
  • Add support for relative file names outside the output path

2.12.0

  • Basic Webpack 2.x support #225

2.11.0

  • Add xhtml option which is turned of by default. When activated it will inject self closed <link href=".." /> tags instead of unclosed <link href=".."> tags. (#255)
  • Add support for webpack placeholders inside the public path e.g. '/dist/[hash]/'. (#249)

2.10.0

  • Add hash field to the chunk object
  • Add compilation field to the templateParam object (#237)
  • Add html-webpack-plugin-before-html-generation event
  • Improve error messages

2.9.0

2.8.2

  • Support relative URLs on Windows (#205)

2.8.1

  • Caching improvements (#204)

2.8.0

  • Add dependency mode for chunksSortMode to sort chunks based on their dependencies with each other

2.7.2

  • Add support for require in js templates

2.7.1

  • Refactoring
  • Fix relative windows path

2.6.5

  • Minor refactoring

2.6.4

  • Fix for "Uncaught TypeError: __webpack_require__(...) is not a function"
  • Fix incomplete cache modules causing "HtmlWebpackPlugin Error: No source available"
  • Fix some issues on Windows

2.6.3

  • Prevent parsing the base template with the html-loader

2.6.2

  • Fix lodash resolve error (#172)

2.6.1

  • Fix missing module (#164)

2.6.0

  • Move compiler to its own file
  • Improve error messages
  • Fix global HTML_WEBPACK_PLUGIN variable

2.5.0

  • Support lodash template's HTML "escape" delimiter (<%- %>)
  • Fix bluebird warning (#130)
  • Fix an issue where incomplete cache modules were used

2.4.0

  • Don't recompile if the assets didn't change

2.3.0

  • Add events html-webpack-plugin-before-html-processing, html-webpack-plugin-after-html-processing, html-webpack-plugin-after-emit to allow other plugins to alter the html this plugin executes

2.2.0

  • Inject css and js even if the html file is incomplete (#135)
  • Update dependencies

2.1.0

  • Synchronize with the stable @1 version

2.0.4

  • Fix minify option
  • Fix missing hash interpolation in publicPath

2.0.3

  • Add support for webpack.BannerPlugin

2.0.2

  • Add support for loaders in templates (#41)
  • Remove templateContent option from configuration
  • Better error messages
  • Update dependencies

1.7.0

  • Add chunksSortMode option to configuration to control how chunks should be sorted before they are included to the html
  • Don't insert async chunks into html (#95)
  • Update dependencies

1.6.2

  • Fix paths on Windows
  • Fix missing hash interpolation in publicPath
  • Allow only false or object in minify configuration option

1.6.1

  • Add size field to the chunk object
  • Fix stylesheet <link>s being discarded when used with "inject: 'head'"
  • Update dependencies

1.6.0

  • Support placing templates in subfolders
  • Don't include chunks with undefined name (#60)
  • Don't include async chunks

1.5.2

  • Update dependencies (lodash)

1.5.1

  • Fix error when manifest is specified (#56)

1.5.0

  • Allow to inject javascript files into the head of the html page
  • Fix error reporting

1.4.0

  • Add favicon.ico option
  • Add html minifcation

1.2.0

  • Set charset using HTML5 meta attribute
  • Reload upon change when using webpack watch mode
  • Generate manifest attribute when using appcache-webpack-plugin
  • Optionally add webpack hash as a query string to resources included in the HTML (hash: true) for cache busting
  • CSS files generated using webpack (for example, by using the extract-text-webpack-plugin) are now automatically included into the generated HTML
  • More detailed information about the files generated by webpack is now available to templates in the o.htmlWebpackPlugin.files attribute. See readme for more details. This new attribute deprecates the old o.htmlWebpackPlugin.assets attribute.
  • The templateContent option can now be a function that returns the template string to use
  • Expose webpack configuration to templates (o.webpackConfig)
  • Sort chunks to honour dependencies between them (useful for use with CommonsChunkPlugin).