Webpack plugin: Use of Html-webpack-plugin

Source: Internet
Author: User

Plugin Address: Https://www.npmjs.com/package/html-webpack-plugin

This plugin is used to simplify the creation of HTML files that serve the Webpack bundle, especially if a hash value is included in the file name, and this value changes every time the compilation occurs. You can either let the plugin help you generate HTML files automatically, or you can use the Lodash template to load the generated bundles, or load the bundles yourself.

Installation

Install this plugin using NPM

$ NPM Install [email protected]--save-dev
Basic Usage

This plugin can help generate HTML files, in the BODY element, using script to contain all your webpack bundles, just configure it in your Webpack configuration file as follows:

var htmlwebpackplugin = require (' Html-webpack-plugin ') var webpackconfig = {  entry: ' index.js ',  output: {    Path: ' Dist ',    filename: ' Index_bundle.js '  },  plugins: [New Htmlwebpackplugin ()]}

This will automatically generate a file named index.html in the Dist directory with the following contents:

<!DOCTYPE HTML><HTML>  <Head>    <MetaCharSet= "UTF-8">    <title>Webpack App</title>  </Head>  <Body>    <Scriptsrc= "Index_bundle.js"></Script>   </Body></HTML>

If you have multiple Webpack entry points, they will be included in the generated script element.

If any of the CSS resources are included in the Webpack output (for example, using Extracttextplugin to refine the CSS), these will be included in the head element of the HTML page with link.

Configuration

A series of configurations can be made to support the following configuration information

    • Title: The title element used to generate the page
    • FileName: The HTML file name of the output, which is index.html by default or can be directly configured with subdirectories.
    • Template: Templates file path, support loader, such as html!. /index.html
    • Inject:true | ' Head ' | ' Body ' | False, inject all the resources into a specific template or TemplateContent, if set to true or body, all JavaScript resources will be placed at the bottom of the BODY element, ' head ' will be placed in the head element In
    • Favicon: Adds a specific favicon path to the output HTML file.
    • Minify: {} | False, pass html-minifier option to minify output
    • Hash:true | False, if true, adds a unique Webpack compilation hash to all included scripts and CSS files, which is useful for unlocking the cache.
    • Cache:true | False, if true, this is the default value, and the file is published only after the file has been modified.
    • Showerrors:true | False, if true, this is the default value, and error messages are written to the HTML page
    • Chunks: Allow only certain blocks to be added (for example, only the unit test block)
    • Chunkssortmode: Allows control of how the block is sorted before it is added to the page, supported by: ' None ' | ' Default ' | {function}-default: ' auto '
    • Excludechunks: Allow skipping of certain blocks (for example, skipping blocks of unit tests)

The following example shows how to use these configurations.

{  entry: ' index.js ',  output: {    path: ' Dist ',    filename: ' index_bundle.js ',    hash:true  },  plugins: [    new Htmlwebpackplugin ({      title: ' My App ',      filename: ' assets/admin.html '    })  ]}
Generate multiple HTML files

Multiple HTML files are generated by adding the plugin multiple times in the configuration file.

{  entry: ' index.js ',  output: {    path: ' 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 custom templates

If the default generated HTML files are not appropriate for your needs, you can create your own defined templates. The convenient way is through the inject option, which is then passed to the custom HTML file. Html-webpack-plugin will automatically inject all required CSS, JS, manifest and favicon files into the tag.

Plugins: [  new Htmlwebpackplugin ({    title: ' Custom template ',    Template: ' my-index.html ',//Load a custom Template     inject: ' body '//inject all scripts into the body   }]

my-index.html file

<!DOCTYPE HTML><HTML>  <Head>    <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/>    <title><%=HtmlWebpackPlugin.options.title%></title>  </Head>  <Body>  </Body></HTML>

If you have a template loader, you can use it to parse this template.

Module: {  loaders: [    {test:/\.hbs$/, Loader: ' Handlebars '}  ]},plugins: [  new Htmlwebpackplugin ({    title: ' Custom template using handlebars ',    Template: ' My-index.hbs ',    inject: ' Body '  }]

Also, if your pattern is a string, you can pass it by using TemplateContent.

Plugins: [  new Htmlwebpackplugin ({    inject:true,    templatecontent:templatecontentstring  })]

If the inject feature does not suit your needs, you want full control over resource placement. You can use the Lodash syntax directly to create your own template using the default template as a starting point.

The TemplateContent option can also be a function to use other languages, such as Jade:

Plugins: [  new Htmlwebpackplugin ({    templatecontent:function (templateparams, compilation) {      //Return Your template content synchronously here       return '. ';    }  })]

or asynchronous version

Plugins: [  new Htmlwebpackplugin ({    templatecontent:function (templateparams, compilation, callback) {      //Return Your template content asynchronously here       callback (null, ' ... ');    }  )]

Note that if you use both template and TemplateContent, the plugin throws an error.

The variable o in the template is the data passed in at render time, and this variable has the following properties:

    • Htmlwebpackplugin: Relevant data for this plugin
    • Htmlwebpackplugin.files: The block name of the resource, the stats object from Webpack, containing the from entry point name to the bundle file name mapping from entry.

  

"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 configure Publicpath in the Webpack configuration file, the correct resources will be reflected

    • Htmlwebpackplugin.options: The configuration passed to the plug-in.
    • The stats object of the Webpack:webpack.
    • Webpackconfig:webpack configuration information. Filter block

      You can use chunks to qualify a specific block.

   

Plugins: [  new Htmlwebpackplugin ({    chunks: [' app ']  })]

You can also use Excludechunks to exclude specific blocks.

Plugins: [  new Htmlwebpackplugin ({    excludechunks: [' Dev-helper ']  })]
Event

Allow other plugins to extend HTML through events.

    • html-webpack-plugin-before-html-processing
    • html-webpack-plugin-after-html-processing
    • html-webpack-plugin-after-emit

How to use:

Compilation.plugin (' html-webpack-plugin-before-html-processing ', function (Htmlplugindata, callback) {  htmlplugindata.html + = ' The Magic footer ';  Callback ();});

       

Webpack plugin: Use of Html-webpack-plugin

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.