Gathering detailed insights and metrics for html-webpack-plugin
Gathering detailed insights and metrics for html-webpack-plugin
Gathering detailed insights and metrics for html-webpack-plugin
Gathering detailed insights and metrics for html-webpack-plugin
@types/html-webpack-plugin
TypeScript definitions for html-webpack-plugin
mini-html-webpack-plugin
A miniature version of html-webpack-plugin with only necessary features
@vxna/mini-html-webpack-template
Minimum viable template for mini-html-webpack-plugin
script-ext-html-webpack-plugin
Enhances html-webpack-plugin functionality with async and defer attributes for script elements
Simplifies creation of HTML files to serve your webpack bundles
npm install html-webpack-plugin
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
10,717 Stars
827 Commits
1,307 Forks
119 Watching
2 Branches
174 Contributors
Updated on 27 Nov 2024
JavaScript (99.93%)
EJS (0.07%)
Cumulative downloads
Total Downloads
Last day
-2.8%
2,385,069
Compared to previous day
Last week
3.3%
12,480,370
Compared to previous week
Last month
11.8%
52,244,734
Compared to previous month
Last year
-14.5%
601,999,074
Compared to previous year
2
26
1 npm i --save-dev html-webpack-plugin
1 yarn add --dev html-webpack-plugin
1 npm i --save-dev html-webpack-plugin@4
1 yarn add --dev html-webpack-plugin@4
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.
Thanks for supporting the ongoing improvements to the html-webpack-plugin!
The html-webpack-plugin
works without configuration.
It's a great addition to the ⚙️ webpack-config-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
head
or body
(different locations ) of same html document.<link rel='preload'>
and <link rel='prefetch'>
<link />
tags to have their media attribute set automatically; useful for providing specific desktop/mobile/print etc. stylesheets that the browser will conditionally downloadmeta
tag to the HTML output. A strict CSP is specifically efficient against XSS attacks.nomodule
attribute to specific injected scripts, which prevents the scripts from being loaded by newer browsers. Good for limiting loads of polyfills.The plugin will generate an HTML5 file for you that includes all your webpack
bundles in the head using script
tags. Just add the plugin to your webpack
config as follows:
webpack.config.js
1const HtmlWebpackPlugin = require("html-webpack-plugin"); 2 3module.exports = { 4 entry: "index.js", 5 output: { 6 path: __dirname + "/dist", 7 filename: "index_bundle.js", 8 }, 9 plugins: [new HtmlWebpackPlugin()], 10};
This will generate a file dist/index.html
containing the following
1<!doctype html> 2<html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>Webpack App</title> 6 <script defer src="index_bundle.js"></script> 7 </head> 8 <body></body> 9</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 mini-css-extract-plugin)
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.
You can pass a hash of configuration options to html-webpack-plugin
.
Allowed values are as follows:
Name | Type | Default | Description |
---|---|---|---|
title | {String} | Webpack App | The title to use for the generated HTML document |
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' . |
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 for details |
templateContent | {string|Function|false} | false | Can be used instead of template to provide an inline template - please read the Writing Your Own Templates section |
templateParameters | {Boolean|Object|Function} | false | Allows to overwrite the parameters used in the template - see example |
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 |
publicPath | {String|'auto'} | 'auto' | The publicPath used for script and link tags |
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" . This also implies "defer", since modules are automatically deferred. |
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'} |
base | {Object|String|false} | false | Inject a base tag. E.g. base: "https://example.com/path/page.html |
minify | {Boolean|Object} | true if mode is 'production' , otherwise false | Controls if and in what ways the output should be minified. See minification below for more details. |
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 |
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' | '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
1{ 2 entry: 'index.js', 3 output: { 4 path: __dirname + '/dist', 5 filename: 'index_bundle.js' 6 }, 7 plugins: [ 8 new HtmlWebpackPlugin({ 9 title: 'My App', 10 filename: 'assets/admin.html' 11 }) 12 ] 13}
To generate more than one HTML file, declare the plugin more than once in your plugins array
webpack.config.js
1{ 2 entry: 'index.js', 3 output: { 4 path: __dirname + '/dist', 5 filename: 'index_bundle.js' 6 }, 7 plugins: [ 8 new HtmlWebpackPlugin(), // Generates default index.html 9 new HtmlWebpackPlugin({ // Also generate a test.html 10 filename: 'test.html', 11 template: 'src/assets/test.html' 12 }) 13 ] 14}
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.
Details of other template loaders are documented here.
1plugins: [ 2 new HtmlWebpackPlugin({ 3 title: "Custom template", 4 // Load a custom template (lodash by default) 5 template: "index.html", 6 }), 7];
index.html
1<!doctype html> 2<html> 3 <head> 4 <meta charset="utf-8" /> 5 <title><%= htmlWebpackPlugin.options.title %></title> 6 </head> 7 <body></body> 8</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 specify the html-loader and use .html
file as template.
webpack.config.js
1module: { 2 loaders: [ 3 { test: /\.hbs$/, loader: "handlebars-loader" } 4 ] 5}, 6plugins: [ 7 new HtmlWebpackPlugin({ 8 title: 'Custom template using Handlebars', 9 template: 'index.hbs' 10 }) 11]
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 by default (you can extend them using the templateParameters
option):
htmlWebpackPlugin
: data specific to this plugin
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.
htmlWebpackPlugin.tags
: the prepared headTags
and bodyTags
Array to render the <base>
, <meta>
, <script>
and <link>
tags.
Can be used directly in templates and literals. For example:
1<html> 2 <head> 3 <%= htmlWebpackPlugin.tags.headTags %> 4 </head> 5 <body> 6 <%= htmlWebpackPlugin.tags.bodyTags %> 7 </body> 8</html>
htmlWebpackPlugin.files
: direct access to the files used during the compilation.
1publicPath: string; 2js: string[]; 3css: string[]; 4manifest?: string; 5favicon?: string;
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).
The template can also be directly inlined directly into the options object.
⚠️ templateContent
does not allow to use webpack loaders for your template and will not watch for template file changes
webpack.config.js
1new HtmlWebpackPlugin({
2 templateContent: `
3 <html>
4 <body>
5 <h1>Hello World</h1>
6 </body>
7 </html>
8 `,
9});
The templateContent
can also access all templateParameters
values.
⚠️ templateContent
does not allow to use webpack loaders for your template and will not watch for template file changes
webpack.config.js
1new HtmlWebpackPlugin({ 2 inject: false, 3 templateContent: ({ htmlWebpackPlugin }) => ` 4 <html> 5 <head> 6 ${htmlWebpackPlugin.tags.headTags} 7 </head> 8 <body> 9 <h1>Hello World</h1> 10 ${htmlWebpackPlugin.tags.bodyTags} 11 </body> 12 </html> 13 `, 14});
To include only certain chunks you can limit the chunks being used
webpack.config.js
1plugins: [ 2 new HtmlWebpackPlugin({ 3 chunks: ["app"], 4 }), 5];
It is also possible to exclude certain chunks by setting the excludeChunks
option
webpack.config.js
1plugins: [ 2 new HtmlWebpackPlugin({ 3 excludeChunks: ["dev-helper"], 4 }), 5];
If the minify
option is set to true
(the default when webpack's mode
is 'production'
),
the generated HTML will be minified using html-minifier-terser
and the following options:
1{ 2 collapseWhitespace: true, 3 keepClosingSlash: true, 4 removeComments: true, 5 removeRedundantAttributes: true, 6 removeScriptTypeAttributes: true, 7 removeStyleLinkTypeAttributes: true, 8 useShortDoctype: true 9}
To use custom html-minifier options
pass an object to minify
instead. This object will not be merged with the defaults above.
To disable minification during production mode set the minify
option to false
.
If the meta
option is set the html-webpack-plugin will inject meta tags.
For the default template the html-webpack-plugin will already provide a default for the viewport
meta tag.
Please take a look at this well maintained list of almost all possible meta tags.
Most meta tags are configured by setting a name
and a content
attribute.
To add those use a key/value pair:
webpack.config.js
1plugins: [ 2 new HtmlWebpackPlugin({ 3 meta: { 4 viewport: "width=device-width, initial-scale=1, shrink-to-fit=no", 5 // Will generate: <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 6 "theme-color": "#4285f4", 7 // Will generate: <meta name="theme-color" content="#4285f4"> 8 }, 9 }), 10];
The http-equiv attribute is essentially used to simulate a HTTP response header.
This format is supported using an object notation which allows you to add any attribute:
webpack.config.js
1plugins: [ 2 new HtmlWebpackPlugin({ 3 meta: { 4 "Content-Security-Policy": { 5 "http-equiv": "Content-Security-Policy", 6 content: "default-src https:", 7 }, 8 // Will generate: <meta http-equiv="Content-Security-Policy" content="default-src https:"> 9 // Which equals to the following http header: `Content-Security-Policy: default-src https:` 10 "set-cookie": { 11 "http-equiv": "set-cookie", 12 content: "name=value; expires=date; path=url", 13 }, 14 // Will generate: <meta http-equiv="set-cookie" content="value; expires=date; path=url"> 15 // Which equals to the following http header: `set-cookie: value; expires=date; path=url` 16 }, 17 }), 18];
When the base
option is used,
html-webpack-plugin will inject a base tag.
By default, a base tag will not be injected.
The following two are identical and will both insert <base href="http://example.com/some/page.html">
:
1new HtmlWebpackPlugin({
2 base: "http://example.com/some/page.html",
3});
1new HtmlWebpackPlugin({ 2 base: { href: "http://example.com/some/page.html" }, 3});
The target
can be specified with the corresponding key:
1new HtmlWebpackPlugin({ 2 base: { 3 href: "http://example.com/some/page.html", 4 target: "_blank", 5 }, 6});
which will inject the element <base href="http://example.com/some/page.html" target="_blank">
.
For long term caching add contenthash
to the filename.
Example:
1plugins: [ 2 new HtmlWebpackPlugin({ 3 filename: "index.[contenthash].html", 4 }), 5];
contenthash
is the hash of the content of the output file.
Refer webpack's Template Strings for more details
To allow other plugins to alter the HTML this plugin executes tapable hooks.
The lib/hooks.js contains all information about which values are passed.
beforeAssetTagGeneration
hook AsyncSeriesWaterfallHook<{
assets: {
publicPath: string,
js: Array<{string}>,
css: Array<{string}>,
favicon?: string | undefined,
manifest?: string | undefined
},
outputName: string,
plugin: HtmlWebpackPlugin
}>
alterAssetTags
hook AsyncSeriesWaterfallHook<{
assetTags: {
scripts: Array<HtmlTagObject>,
styles: Array<HtmlTagObject>,
meta: Array<HtmlTagObject>,
},
publicPath: string,
outputName: string,
plugin: HtmlWebpackPlugin
}>
alterAssetTagGroups
hook AsyncSeriesWaterfallHook<{
headTags: Array<HtmlTagObject | HtmlTagObject>,
bodyTags: Array<HtmlTagObject | HtmlTagObject>,
publicPath: string,
outputName: string,
plugin: HtmlWebpackPlugin
}>
afterTemplateExecution
hook AsyncSeriesWaterfallHook<{
html: string,
headTags: Array<HtmlTagObject | HtmlTagObject>,
bodyTags: Array<HtmlTagObject | HtmlTagObject>,
outputName: string,
plugin: HtmlWebpackPlugin,
}>
beforeEmit
hook AsyncSeriesWaterfallHook<{
html: string,
outputName: string,
plugin: HtmlWebpackPlugin,
}>
afterEmit
hook AsyncSeriesWaterfallHook<{
outputName: string,
plugin: HtmlWebpackPlugin
}>
Example implementation: webpack-subresource-integrity
plugin.js
1// If your plugin is direct dependent to the html webpack plugin: 2const HtmlWebpackPlugin = require("html-webpack-plugin"); 3// If your plugin is using html-webpack-plugin as an optional dependency 4// you can use https://github.com/tallesl/node-safe-require instead: 5const HtmlWebpackPlugin = require("safe-require")("html-webpack-plugin"); 6 7class MyPlugin { 8 apply(compiler) { 9 compiler.hooks.compilation.tap("MyPlugin", (compilation) => { 10 console.log("The compiler is starting a new compilation..."); 11 12 // Static Plugin interface |compilation |HOOK NAME | register listener 13 HtmlWebpackPlugin.getCompilationHooks(compilation).beforeEmit.tapAsync( 14 "MyPlugin", // <-- Set a meaningful name here for stacktraces 15 (data, cb) => { 16 // Manipulate the content 17 data.html += "The Magic Footer"; 18 // Tell webpack to move on 19 cb(null, data); 20 }, 21 ); 22 }); 23 } 24} 25 26module.exports = MyPlugin;
webpack.config.js
1plugins: [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 beforeEmit
event
Jan Nicklas |
Thomas Sileghem |
Thank you to all our backers!
If you want to support the project as well become a sponsor or a a backer.
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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
8 commit(s) and 9 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
5 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
Found 7/30 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More