You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

667 lines
39 KiB

1 month ago
  1. [![npm][npm]][npm-url]
  2. [![node][node]][node-url]
  3. ![npm](https://img.shields.io/npm/dw/html-webpack-plugin.svg)
  4. [![tests][tests]][tests-url]
  5. [![Backers on Open Collective](https://opencollective.com/html-webpack-plugin/backers/badge.svg)](#backers)
  6. [![Sponsors on Open Collective](https://opencollective.com/html-webpack-plugin/sponsors/badge.svg)](#sponsors)
  7. <div align="center">
  8. <img width="200" height="200" src="https://www.w3.org/html/logo/downloads/HTML5_Badge.svg">
  9. <a href="https://github.com/webpack/webpack">
  10. <img width="200" height="200"
  11. src="https://webpack.js.org/assets/icon-square-big.svg">
  12. </a>
  13. <div>
  14. <img width="100" height="100" title="Webpack Plugin" src="http://michael-ciniawsky.github.io/postcss-load-plugins/logo.svg">
  15. </div>
  16. <h1>HTML Webpack Plugin</h1>
  17. <p>Plugin that simplifies creation of HTML files to serve your bundles</p>
  18. </div>
  19. <h2 align="center">Install</h2>
  20. <h3>Webpack 5</h3>
  21. ```bash
  22. npm i --save-dev html-webpack-plugin
  23. ```
  24. ```bash
  25. yarn add --dev html-webpack-plugin
  26. ```
  27. <h3>Webpack 4</h3>
  28. ```bash
  29. npm i --save-dev html-webpack-plugin@4
  30. ```
  31. ```bash
  32. yarn add --dev html-webpack-plugin@4
  33. ```
  34. This is a [webpack](http://webpack.js.org/) 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
  35. your own template using `lodash` templates or use your own loader.
  36. <h2 align="center">Sponsors</h2>
  37. <a href="https://opencollective.com/html-webpack-plugin/sponsor/0/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/0/avatar.svg"></a>
  38. <a href="https://opencollective.com/html-webpack-plugin/sponsor/1/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/1/avatar.svg"></a>
  39. <a href="https://opencollective.com/html-webpack-plugin/sponsor/2/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/2/avatar.svg"></a>
  40. <a href="https://opencollective.com/html-webpack-plugin/sponsor/3/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/3/avatar.svg"></a>
  41. <a href="https://opencollective.com/html-webpack-plugin/sponsor/4/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/4/avatar.svg"></a>
  42. <a href="https://opencollective.com/html-webpack-plugin/sponsor/5/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/5/avatar.svg"></a>
  43. <a href="https://opencollective.com/html-webpack-plugin/sponsor/6/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/6/avatar.svg"></a>
  44. <a href="https://opencollective.com/html-webpack-plugin/sponsor/7/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/7/avatar.svg"></a>
  45. <a href="https://opencollective.com/html-webpack-plugin/sponsor/8/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/8/avatar.svg"></a>
  46. <a href="https://opencollective.com/html-webpack-plugin/sponsor/9/website" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/sponsor/9/avatar.svg"></a>
  47. Thanks for supporting the ongoing improvements to the html-webpack-plugin!
  48. <h2 align="center">Zero Config</h2>
  49. The `html-webpack-plugin` works without configuration.
  50. It's a great addition to the [⚙️ webpack-config-plugins](https://github.com/namics/webpack-config-plugins/blob/master/README.md#zero-config-webpack-dev-server-example).
  51. <h2 align="center">Plugins</h2>
  52. The `html-webpack-plugin` provides [hooks](https://github.com/jantimon/html-webpack-plugin#events) to extend it to your needs. There are already some really powerful plugins which can be integrated with zero configuration
  53. - [webpack-subresource-integrity](https://www.npmjs.com/package/webpack-subresource-integrity) for enhanced asset security
  54. - [appcache-webpack-plugin](https://github.com/lettertwo/appcache-webpack-plugin) for iOS and Android offline usage
  55. - [favicons-webpack-plugin](https://github.com/jantimon/favicons-webpack-plugin) which generates favicons and icons for iOS, Android and desktop browsers
  56. - [html-webpack-harddisk-plugin](https://github.com/jantimon/html-webpack-harddisk-plugin) can be used to always write to disk the html file, useful when webpack-dev-server / HMR are being used
  57. - [html-webpack-inline-svg-plugin](https://github.com/thegc/html-webpack-inline-svg-plugin) to inline SVGs in the resulting HTML file.
  58. - [html-webpack-exclude-assets-plugin](https://github.com/jamesjieye/html-webpack-exclude-assets-plugin) for excluding assets using regular expressions
  59. - [html-webpack-include-assets-plugin](https://github.com/jharris4/html-webpack-include-assets-plugin) for including lists of js or css file paths (such as those copied by the copy-webpack-plugin).
  60. - [html-webpack-injector](https://github.com/thearchitgarg/html-webpack-injector) to inject chunks in `head` or `body` (different locations ) of same html document.
  61. - [resource-hints-webpack-plugin](https://github.com/jantimon/resource-hints-webpack-plugin) to add resource hints for faster initial page loads using `<link rel='preload'>` and `<link rel='prefetch'>`
  62. - [link-media-html-webpack-plugin](https://github.com/yaycmyk/link-media-html-webpack-plugin) allows for injected stylesheet `<link />` tags to have their media attribute set automatically; useful for providing specific desktop/mobile/print etc. stylesheets that the browser will conditionally download
  63. - [html-webpack-inline-style-plugin](https://github.com/djaax/html-webpack-inline-style-plugin) for inlining styles to HTML elements using [juice](https://github.com/Automattic/juice). Useful for email generation automatisation.
  64. - [html-webpack-exclude-empty-assets-plugin](https://github.com/KnisterPeter/html-webpack-exclude-empty-assets-plugin) removes empty assets from being added to the html. This fixes some problems with extract-text-plugin with webpack 4.
  65. - [webpack-concat-plugin](https://github.com/hxlniada/webpack-concat-plugin) for concat and uglify files that needn't to be webpack bundles(for legacy files) and inject to html-webpack-plugin.
  66. - [html-webpack-link-type-plugin](https://github.com/steadyapp/html-webpack-link-type-plugin) adds a configurable mimetype to resources injected as links (such as adding type="text/css" to external stylesheets) for compatibility with "strict mode".
  67. - [csp-html-webpack-plugin](https://github.com/slackhq/csp-html-webpack-plugin) to add [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) meta tags to the HTML output
  68. - [strict-csp-html-webpack-plugin](https://github.com/google/strict-csp/tree/main/strict-csp-html-webpack-plugin) to add a [**strict** Content-Security-Policy (CSP)](https://web.dev) as a `meta` tag to the HTML output. A strict CSP is specifically efficient against XSS attacks.
  69. - [webpack-nomodule-plugin](https://github.com/swimmadude66/webpack-nomodule-plugin) allows you to add a `nomodule` attribute to specific injected scripts, which prevents the scripts from being loaded by newer browsers. Good for limiting loads of polyfills.
  70. - [html-webpack-skip-assets-plugin](https://github.com/swimmadude66/html-webpack-skip-assets-plugin) Skip adding certain output files to the html file. Built as a drop-in replacement for [html-webpack-exclude-assets-plugin](https://www.npmjs.com/package/html-webpack-exclude-assets-plugin) and works with newer [html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin) versions
  71. - [html-webpack-inject-preload](https://github.com/principalstudio/html-webpack-inject-preload) allows to add preload links &lt;link rel='preload'> anywhere you want.
  72. - [inject-body-webpack-plugin](https://github.com/Jaid/inject-body-webpack-plugin) is a simple method of injecting a custom HTML string into the body.
  73. - [html-webpack-plugin-django](https://github.com/TommasoAmici/html-webpack-plugin-django) a Webpack plugin to inject Django static tags.
  74. - [html-webpack-inject-attributes-plugin](https://github.com/dyw934854565/html-webpack-inject-attributes-plugin) add extra attributes to inject assetTags.
  75. - [js-entry-webpack-plugin](https://github.com/liam61/html-webpack-plugin) creates webpack bundles into your js entry
  76. <h2 align="center">Usage</h2>
  77. The plugin will generate an HTML5 file for you that includes all your `webpack`
  78. bundles in the head using `script` tags. Just add the plugin to your `webpack`
  79. config as follows:
  80. **webpack.config.js**
  81. ```js
  82. const HtmlWebpackPlugin = require("html-webpack-plugin");
  83. module.exports = {
  84. entry: "index.js",
  85. output: {
  86. path: __dirname + "/dist",
  87. filename: "index_bundle.js",
  88. },
  89. plugins: [new HtmlWebpackPlugin()],
  90. };
  91. ```
  92. This will generate a file `dist/index.html` containing the following
  93. ```html
  94. <!doctype html>
  95. <html>
  96. <head>
  97. <meta charset="utf-8" />
  98. <title>Webpack App</title>
  99. <script defer src="index_bundle.js"></script>
  100. </head>
  101. <body></body>
  102. </html>
  103. ```
  104. If you have multiple `webpack` entry points, they will all be included with `script` tags in the generated HTML.
  105. If you have any CSS assets in webpack's output (for example, CSS extracted with the [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin))
  106. then these will be included with `<link>` tags in the HTML head.
  107. If you have plugins that make use of it, `html-webpack-plugin` should be ordered first before any of the integrated Plugins.
  108. <h2 align="center">Options</h2>
  109. You can pass a hash of configuration options to `html-webpack-plugin`.
  110. Allowed values are as follows:
  111. | Name | Type | Default | Description |
  112. | :----------------------: | :--------------------------------------------------: | :---------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  113. | **`title`** | `{String}` | `Webpack App` | The title to use for the generated HTML document |
  114. | **`filename`** | `{String\|Function}` | `'index.html'` | The file to write the HTML to. Defaults to `index.html`. You can specify a subdirectory here too (eg: `assets/admin.html`). The `[name]` placeholder will be replaced with the entry name. Can also be a function e.g. `(entryName) => entryName + '.html'`. |
  115. | **`template`** | `{String}` | `` | `webpack` relative or absolute path to the template. By default it will use `src/index.ejs` if it exists. Please see the [docs](https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md) for details |
  116. | **`templateContent`** | `{string\|Function\|false}` | false | Can be used instead of `template` to provide an inline template - please read the [Writing Your Own Templates](https://github.com/jantimon/html-webpack-plugin#writing-your-own-templates) section |
  117. | **`templateParameters`** | `{Boolean\|Object\|Function}` | `false` | Allows to overwrite the parameters used in the template - see [example](https://github.com/jantimon/html-webpack-plugin/tree/master/examples/template-parameters) |
  118. | **`inject`** | `{Boolean\|String}` | `true` | `true \|\| 'head' \|\| 'body' \|\| false` Inject all assets into the given `template` or `templateContent`. When passing `'body'` all javascript resources will be placed at the bottom of the body element. `'head'` will place the scripts in the head element. Passing `true` will add it to the head/body depending on the `scriptLoading` option. Passing `false` will disable automatic injections. - see the [inject:false example](https://github.com/jantimon/html-webpack-plugin/tree/master/examples/custom-insertion-position) |
  119. | **`publicPath`** | `{String\|'auto'}` | `'auto'` | The publicPath used for script and link tags |
  120. | **`scriptLoading`** | `{'blocking'\|'defer'\|'module'\|'systemjs-module'}` | `'defer'` | Modern browsers support non blocking javascript loading (`'defer'`) to improve the page startup performance. Setting to `'module'` adds attribute [`type="module"`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#applying_the_module_to_your_html). This also implies "defer", since modules are automatically deferred. |
  121. | **`favicon`** | `{String}` | `` | Adds the given favicon path to the output HTML |
  122. | **`meta`** | `{Object}` | `{}` | Allows to inject `meta`-tags. E.g. `meta: {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}` |
  123. | **`base`** | `{Object\|String\|false}` | `false` | Inject a [`base`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) tag. E.g. `base: "https://example.com/path/page.html` |
  124. | **`minify`** | `{Boolean\|Object}` | `true` if `mode` is `'production'`, otherwise `false` | Controls if and in what ways the output should be minified. See [minification](#minification) below for more details. |
  125. | **`hash`** | `{Boolean}` | `false` | If `true` then append a unique `webpack` compilation hash to all included scripts and CSS files (i.e. `main.js?hash=compilation_hash`). This is useful for cache busting |
  126. | **`cache`** | `{Boolean}` | `true` | Emit the file only if it was changed |
  127. | **`showErrors`** | `{Boolean}` | `true` | Errors details will be written into the HTML page |
  128. | **`chunks`** | `{?}` | `?` | Allows you to add only some chunks (e.g only the unit-test chunk) |
  129. | **`chunksSortMode`** | `{String\|Function}` | `auto` | Allows to control how chunks should be sorted before they are included to the HTML. Allowed values are `'none' \| 'auto' \| 'manual' \| {Function}` |
  130. | **`excludeChunks`** | `{Array.<string>}` | `` | Allows you to skip some chunks (e.g don't add the unit-test chunk) |
  131. | **`xhtml`** | `{Boolean}` | `false` | If `true` render the `link` tags as self-closing (XHTML compliant) |
  132. Here's an example webpack config illustrating how to use these options
  133. **webpack.config.js**
  134. ```js
  135. {
  136. entry: 'index.js',
  137. output: {
  138. path: __dirname + '/dist',
  139. filename: 'index_bundle.js'
  140. },
  141. plugins: [
  142. new HtmlWebpackPlugin({
  143. title: 'My App',
  144. filename: 'assets/admin.html'
  145. })
  146. ]
  147. }
  148. ```
  149. ### Generating Multiple HTML Files
  150. To generate more than one HTML file, declare the plugin more than
  151. once in your plugins array
  152. **webpack.config.js**
  153. ```js
  154. {
  155. entry: 'index.js',
  156. output: {
  157. path: __dirname + '/dist',
  158. filename: 'index_bundle.js'
  159. },
  160. plugins: [
  161. new HtmlWebpackPlugin(), // Generates default index.html
  162. new HtmlWebpackPlugin({ // Also generate a test.html
  163. filename: 'test.html',
  164. template: 'src/assets/test.html'
  165. })
  166. ]
  167. }
  168. ```
  169. ### Writing Your Own Templates
  170. If the default generated HTML doesn't meet your needs you can supply
  171. your own template. The easiest way is to use the `template` option and pass a custom HTML file.
  172. The html-webpack-plugin will automatically inject all necessary CSS, JS, manifest
  173. and favicon files into the markup.
  174. Details of other template loaders are [documented here](https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md).
  175. ```js
  176. plugins: [
  177. new HtmlWebpackPlugin({
  178. title: "Custom template",
  179. // Load a custom template (lodash by default)
  180. template: "index.html",
  181. }),
  182. ];
  183. ```
  184. **index.html**
  185. ```html
  186. <!doctype html>
  187. <html>
  188. <head>
  189. <meta charset="utf-8" />
  190. <title><%= htmlWebpackPlugin.options.title %></title>
  191. </head>
  192. <body></body>
  193. </html>
  194. ```
  195. If you already have a template loader, you can use it to parse the template.
  196. Please note that this will also happen if you specify the html-loader and use `.html` file as template.
  197. **webpack.config.js**
  198. ```js
  199. module: {
  200. loaders: [
  201. { test: /\.hbs$/, loader: "handlebars-loader" }
  202. ]
  203. },
  204. plugins: [
  205. new HtmlWebpackPlugin({
  206. title: 'Custom template using Handlebars',
  207. template: 'index.hbs'
  208. })
  209. ]
  210. ```
  211. 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](https://github.com/jaketrent/html-webpack-template/blob/86f285d5c790a6c15263f5cc50fd666d51f974fd/index.html) of the [html-webpack-template project](https://github.com/jaketrent/html-webpack-template) as a starting point for writing your own.
  212. The following variables are available in the template by default (you can extend them using the `templateParameters` option):
  213. - `htmlWebpackPlugin`: data specific to this plugin
  214. - `htmlWebpackPlugin.options`: the options hash that was passed to
  215. the plugin. In addition to the options actually used by this plugin,
  216. you can use this hash to pass arbitrary data through to your template.
  217. - `htmlWebpackPlugin.tags`: the prepared `headTags` and `bodyTags` Array to render the `<base>`, `<meta>`, `<script>` and `<link>` tags.
  218. Can be used directly in templates and literals. For example:
  219. ```html
  220. <html>
  221. <head>
  222. <%= htmlWebpackPlugin.tags.headTags %>
  223. </head>
  224. <body>
  225. <%= htmlWebpackPlugin.tags.bodyTags %>
  226. </body>
  227. </html>
  228. ```
  229. - `htmlWebpackPlugin.files`: direct access to the files used during the compilation.
  230. ```typescript
  231. publicPath: string;
  232. js: string[];
  233. css: string[];
  234. manifest?: string;
  235. favicon?: string;
  236. ```
  237. - `webpackConfig`: the webpack configuration that was used for this compilation. This
  238. can be used, for example, to get the `publicPath` (`webpackConfig.output.publicPath`).
  239. - `compilation`: the webpack [compilation object](https://webpack.js.org/api/compilation-object/).
  240. This can be used, for example, to get the contents of processed assets and inline them
  241. directly in the page, through `compilation.assets[...].source()`
  242. (see [the inline template example](examples/inline/template.pug)).
  243. The template can also be directly inlined directly into the options object.
  244. ⚠️ **`templateContent` does not allow to use webpack loaders for your template and will not watch for template file changes**
  245. **webpack.config.js**
  246. ```js
  247. new HtmlWebpackPlugin({
  248. templateContent: `
  249. <html>
  250. <body>
  251. <h1>Hello World</h1>
  252. </body>
  253. </html>
  254. `,
  255. });
  256. ```
  257. The `templateContent` can also access all `templateParameters` values.
  258. ⚠️ **`templateContent` does not allow to use webpack loaders for your template and will not watch for template file changes**
  259. **webpack.config.js**
  260. ```js
  261. new HtmlWebpackPlugin({
  262. inject: false,
  263. templateContent: ({ htmlWebpackPlugin }) => `
  264. <html>
  265. <head>
  266. ${htmlWebpackPlugin.tags.headTags}
  267. </head>
  268. <body>
  269. <h1>Hello World</h1>
  270. ${htmlWebpackPlugin.tags.bodyTags}
  271. </body>
  272. </html>
  273. `,
  274. });
  275. ```
  276. ### Filtering Chunks
  277. To include only certain chunks you can limit the chunks being used
  278. **webpack.config.js**
  279. ```js
  280. plugins: [
  281. new HtmlWebpackPlugin({
  282. chunks: ["app"],
  283. }),
  284. ];
  285. ```
  286. It is also possible to exclude certain chunks by setting the `excludeChunks` option
  287. **webpack.config.js**
  288. ```js
  289. plugins: [
  290. new HtmlWebpackPlugin({
  291. excludeChunks: ["dev-helper"],
  292. }),
  293. ];
  294. ```
  295. ### Minification
  296. If the `minify` option is set to `true` (the default when webpack's `mode` is `'production'`),
  297. the generated HTML will be minified using [html-minifier-terser](https://github.com/DanielRuf/html-minifier-terser)
  298. and the following options:
  299. ```js
  300. {
  301. collapseWhitespace: true,
  302. keepClosingSlash: true,
  303. removeComments: true,
  304. removeRedundantAttributes: true,
  305. removeScriptTypeAttributes: true,
  306. removeStyleLinkTypeAttributes: true,
  307. useShortDoctype: true
  308. }
  309. ```
  310. To use custom [html-minifier options](https://github.com/DanielRuf/html-minifier-terser#options-quick-reference)
  311. pass an object to `minify` instead. This object will not be merged with the defaults above.
  312. To disable minification during production mode set the `minify` option to `false`.
  313. ### Meta Tags
  314. If the `meta` option is set the html-webpack-plugin will inject meta tags.
  315. For the default template the html-webpack-plugin will already provide a default for the `viewport` meta tag.
  316. Please take a look at this well maintained list of almost all [possible meta tags](https://github.com/joshbuchea/HEAD#meta).
  317. #### name/content meta tags
  318. Most meta tags are configured by setting a `name` and a `content` attribute.
  319. To add those use a key/value pair:
  320. **webpack.config.js**
  321. ```js
  322. plugins: [
  323. new HtmlWebpackPlugin({
  324. meta: {
  325. viewport: "width=device-width, initial-scale=1, shrink-to-fit=no",
  326. // Will generate: <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  327. "theme-color": "#4285f4",
  328. // Will generate: <meta name="theme-color" content="#4285f4">
  329. },
  330. }),
  331. ];
  332. ```
  333. #### Simulate http response headers
  334. The **http-equiv** attribute is essentially used to simulate a HTTP response header.
  335. This format is supported using an object notation which allows you to add any attribute:
  336. **webpack.config.js**
  337. ```js
  338. plugins: [
  339. new HtmlWebpackPlugin({
  340. meta: {
  341. "Content-Security-Policy": {
  342. "http-equiv": "Content-Security-Policy",
  343. content: "default-src https:",
  344. },
  345. // Will generate: <meta http-equiv="Content-Security-Policy" content="default-src https:">
  346. // Which equals to the following http header: `Content-Security-Policy: default-src https:`
  347. "set-cookie": {
  348. "http-equiv": "set-cookie",
  349. content: "name=value; expires=date; path=url",
  350. },
  351. // Will generate: <meta http-equiv="set-cookie" content="value; expires=date; path=url">
  352. // Which equals to the following http header: `set-cookie: value; expires=date; path=url`
  353. },
  354. }),
  355. ];
  356. ```
  357. ### Base Tag
  358. When the `base` option is used,
  359. html-webpack-plugin will inject a [base tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base).
  360. By default, a base tag will not be injected.
  361. The following two are identical and will both insert `<base href="http://example.com/some/page.html">`:
  362. ```js
  363. new HtmlWebpackPlugin({
  364. base: "http://example.com/some/page.html",
  365. });
  366. ```
  367. ```js
  368. new HtmlWebpackPlugin({
  369. base: { href: "http://example.com/some/page.html" },
  370. });
  371. ```
  372. The `target` can be specified with the corresponding key:
  373. ```js
  374. new HtmlWebpackPlugin({
  375. base: {
  376. href: "http://example.com/some/page.html",
  377. target: "_blank",
  378. },
  379. });
  380. ```
  381. which will inject the element `<base href="http://example.com/some/page.html" target="_blank">`.
  382. ### Long Term Caching
  383. For long term caching add `contenthash` to the filename.
  384. **Example:**
  385. ```js
  386. plugins: [
  387. new HtmlWebpackPlugin({
  388. filename: "index.[contenthash].html",
  389. }),
  390. ];
  391. ```
  392. `contenthash` is the hash of the content of the output file.
  393. Refer webpack's [Template Strings](https://webpack.js.org/configuration/output/#template-strings) for more details
  394. ### Events
  395. To allow other [plugins](https://github.com/webpack/docs/wiki/plugins) to alter the HTML this plugin executes
  396. [tapable](https://github.com/webpack/tapable/tree/master) hooks.
  397. The [lib/hooks.js](https://github.com/jantimon/html-webpack-plugin/blob/master/lib/hooks.js) contains all information
  398. about which values are passed.
  399. [![Concept flow uml](https://raw.githubusercontent.com/jantimon/html-webpack-plugin/master/flow.png)](https://github.com/jantimon/html-webpack-plugin/blob/master/flow.puml)
  400. #### `beforeAssetTagGeneration` hook
  401. ```
  402. AsyncSeriesWaterfallHook<{
  403. assets: {
  404. publicPath: string,
  405. js: Array<{string}>,
  406. css: Array<{string}>,
  407. favicon?: string | undefined,
  408. manifest?: string | undefined
  409. },
  410. outputName: string,
  411. plugin: HtmlWebpackPlugin
  412. }>
  413. ```
  414. #### `alterAssetTags` hook
  415. ```
  416. AsyncSeriesWaterfallHook<{
  417. assetTags: {
  418. scripts: Array<HtmlTagObject>,
  419. styles: Array<HtmlTagObject>,
  420. meta: Array<HtmlTagObject>,
  421. },
  422. publicPath: string,
  423. outputName: string,
  424. plugin: HtmlWebpackPlugin
  425. }>
  426. ```
  427. #### `alterAssetTagGroups` hook
  428. ```
  429. AsyncSeriesWaterfallHook<{
  430. headTags: Array<HtmlTagObject | HtmlTagObject>,
  431. bodyTags: Array<HtmlTagObject | HtmlTagObject>,
  432. publicPath: string,
  433. outputName: string,
  434. plugin: HtmlWebpackPlugin
  435. }>
  436. ```
  437. #### `afterTemplateExecution` hook
  438. ```
  439. AsyncSeriesWaterfallHook<{
  440. html: string,
  441. headTags: Array<HtmlTagObject | HtmlTagObject>,
  442. bodyTags: Array<HtmlTagObject | HtmlTagObject>,
  443. outputName: string,
  444. plugin: HtmlWebpackPlugin,
  445. }>
  446. ```
  447. #### `beforeEmit` hook
  448. ```
  449. AsyncSeriesWaterfallHook<{
  450. html: string,
  451. outputName: string,
  452. plugin: HtmlWebpackPlugin,
  453. }>
  454. ```
  455. #### `afterEmit` hook
  456. ```
  457. AsyncSeriesWaterfallHook<{
  458. outputName: string,
  459. plugin: HtmlWebpackPlugin
  460. }>
  461. ```
  462. Example implementation: [webpack-subresource-integrity](https://www.npmjs.com/package/webpack-subresource-integrity)
  463. **plugin.js**
  464. ```js
  465. // If your plugin is direct dependent to the html webpack plugin:
  466. const HtmlWebpackPlugin = require("html-webpack-plugin");
  467. // If your plugin is using html-webpack-plugin as an optional dependency
  468. // you can use https://github.com/tallesl/node-safe-require instead:
  469. const HtmlWebpackPlugin = require("safe-require")("html-webpack-plugin");
  470. class MyPlugin {
  471. apply(compiler) {
  472. compiler.hooks.compilation.tap("MyPlugin", (compilation) => {
  473. console.log("The compiler is starting a new compilation...");
  474. // Static Plugin interface |compilation |HOOK NAME | register listener
  475. HtmlWebpackPlugin.getCompilationHooks(compilation).beforeEmit.tapAsync(
  476. "MyPlugin", // <-- Set a meaningful name here for stacktraces
  477. (data, cb) => {
  478. // Manipulate the content
  479. data.html += "The Magic Footer";
  480. // Tell webpack to move on
  481. cb(null, data);
  482. },
  483. );
  484. });
  485. }
  486. }
  487. module.exports = MyPlugin;
  488. ```
  489. **webpack.config.js**
  490. ```js
  491. plugins: [new MyPlugin({ options: "" })];
  492. ```
  493. Note that the callback must be passed the HtmlWebpackPluginData in order to pass this onto any other plugins listening on the same `beforeEmit` event
  494. <h2 align="center">Maintainers</h2>
  495. <table>
  496. <tbody>
  497. <tr>
  498. <td align="center">
  499. <img width="150" height="150"
  500. src="https://avatars3.githubusercontent.com/u/4113649?v=3&s=150">
  501. </br>
  502. <a href="https://github.com/jantimon">Jan Nicklas</a>
  503. </td>
  504. <td align="center">
  505. <img width="150" height="150"
  506. src="https://avatars2.githubusercontent.com/u/4112409?v=3&s=150">
  507. </br>
  508. <a href="https://github.com/mastilver">Thomas Sileghem</a>
  509. </td>
  510. </tr>
  511. <tbody>
  512. </table>
  513. ## Backers
  514. Thank you to all our backers!
  515. If you want to support the project as well [become a sponsor](https://opencollective.com/html-webpack-plugin#sponsor) or a [a backer](https://opencollective.com/html-webpack-plugin#backer).
  516. <a href="https://opencollective.com/html-webpack-plugin/backer/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/0/avatar.svg?requireActive=false"></a>
  517. <a href="https://opencollective.com/html-webpack-plugin/backer/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/1/avatar.svg?requireActive=false"></a>
  518. <a href="https://opencollective.com/html-webpack-plugin/backer/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/2/avatar.svg?requireActive=false"></a>
  519. <a href="https://opencollective.com/html-webpack-plugin/backer/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/3/avatar.svg?requireActive=false"></a>
  520. <a href="https://opencollective.com/html-webpack-plugin/backer/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/4/avatar.svg?requireActive=false"></a>
  521. <a href="https://opencollective.com/html-webpack-plugin/backer/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/5/avatar.svg?requireActive=false"></a>
  522. <a href="https://opencollective.com/html-webpack-plugin/backer/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/6/avatar.svg?requireActive=false"></a>
  523. <a href="https://opencollective.com/html-webpack-plugin/backer/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/7/avatar.svg?requireActive=false"></a>
  524. <a href="https://opencollective.com/html-webpack-plugin/backer/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/8/avatar.svg?requireActive=false"></a>
  525. <a href="https://opencollective.com/html-webpack-plugin/backer/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/html-webpack-plugin/backer/9/avatar.svg?requireActive=false"></a>
  526. ## Contributors
  527. This project exists thanks to all the people who contribute.
  528. You're free to contribute to this project by submitting [issues](https://github.com/jantimon/html-webpack-plugin/issues) and/or [pull requests](https://github.com/jantimon/html-webpack-plugin/pulls). This project is test-driven, so keep in mind that every change and new feature should be covered by tests.
  529. <a href="https://github.com/jantimon/html-webpack-plugin/graphs/contributors"><img src="https://opencollective.com/html-webpack-plugin/contributors.svg?width=890&button=false" /></a>
  530. [npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg
  531. [npm-url]: https://npmjs.com/package/html-webpack-plugin
  532. [node]: https://img.shields.io/node/v/html-webpack-plugin.svg
  533. [node-url]: https://nodejs.org
  534. [tests]: https://github.com/jantimon/html-webpack-plugin/workflows/CI/badge.svg
  535. [tests-url]: https://github.com/jantimon/html-webpack-plugin/actions?query=workflow%3ACI