HTML – webpack – plugin plug-in

  1. Dynamically generate HTML files and automatically import JS files

  2. Static files do not need to load JS or CSS files. By setting the entry file, js files can be added automatically, and related CSS files can be imported in JS

  3. At the same time, modify the naming rule of the generated JS file to use the hash code to name the JS file

  4. You can let the browser cache the content when there are no changes, and invalidate the browser cache when there are changes and redeploy

The installation

cnpm install html-webpack-plugin --save-dev
Copy the code

Common parameters

title

The title of the generated HTML document that is packaged

Configure the, it will not replace the content of the title element in a specified template file, unless the HTML template file using the template engine syntax to obtain the values of configuration items < % = htmlWebpackPlugin. Options. The title % >

Template: indicates the path of a template

Specify which HTML file template your generated file will depend on. The template type can be HTML, JADE, EJS, etc

Note that if you want to use custom template files, you need to install the corresponding Loader

Ejs-loader is used by default if no loader is specified for the template file. For example, if template: ‘./index.html’ does not specify any loader for.html, use ejs-loader

Filename: indicates a relative path

The file name of the output file, which defaults to index.html, and can also specify a directory location for the output file (for example, ‘HTML /index.html’)

HTML file filename configuration directory is relative to the webpackConfig output. The path, the path is not relative to the current project directory structure

Specify that the link and script paths in the generated HTML file contents are relative to the build directory. Write paths are usually relative to the build directory

templateContent: string|function

You can specify the contents of a template and cannot coexist with it. When configured to function, an HTML string can be returned either directly or asynchronously

minify: {…. }|false

Pass the HTML-minifier option to minify output, false means that HTML compression is not used

Minify: {collapseWhitespace: true, collapseWhitespace removeAttributeQuotes: true // Remove quotes},Copy the code
  • CaseSensitive (default false) : Handles attributes case-sensitive (for custom HTML tags)

  • CollapseBooleanAttributes (default false) : omitted attribute values from a Boolean attribute

  • collapseInlineTagWhitespace Don’t leave any spaces between display:inline; elements when collapsing. Must be used in conjunction with collapseWhitespace=true false

  • CollapseWhitespace do not leave any space between displays: inline; Elements at crash time. Must be used with folded space =true? false

  • ConservativeCollapse always folds down to 1 space (never delete it completely). Must be used with folded space =true? false

  • CustomAttrAssign allows regular expression arrays that support custom attribute assignment expressions. (e.g. ‘<div flex? =”{{mode ! = cover}}”>’) [ ]

  • CustomAttrCollapse Regex specifies custom properties to remove new lines from (for example, /ng-class/).

  • CustomAttrSurround allows regular expression arrays that support custom attribute enveloping expressions (e.g. <input {{#if value}}checked=”checked”{{/if}}>) []

  • CustomEventAttributes allows regular expression arrays for minifyJS to support customEventAttributes (for example, ng-click) [/^on[a-z]{3,}$/]

  • DecodeEntities use direct Unicode characters whenever possible. false

  • Html5 analyzes input according to the HTML5 specification. true

  • IgnoreCustomComments An array of regular expressions that allows certain comments to be ignored when matched. / / ^!

  • IgnoreCustomFragments Allows regular expression arrays of fragments to be ignored when matched (for example,{{… }}, etc.). [ /<%[\s\S]?%>/, /
    / ]

  • IncludeAutoGeneratedTags insert tags generated by the HTML parser. true

  • KeepClosingSlash preserves the trailing slash of the singleton element. false

  • MaxLineLength Specifies the maximum line length. The compressed output will be wrapped at the valid HTML split point.

  • MinifyCSS Miniaturize CSS style elements and style properties (usesclean-CSS) False (Could betrue, Object,Function(text))

  • False (Could betrue, Object,Function(text, inline)) minifyJS miniaturizes JavaScript(using UglifyJS) in script elements and event attributes

  • False (Could beString, Object,Function(text)) minifyURLs shrink urls in various attributes (using relateURL)

  • PreserveLineBreaks Always break to 1 line when Spaces between tags include line breaks (never delete them entirely). Must be used with folded space =true? false

  • PreventAttributesEscaping prevent overflow of attribute values. false

  • Comment on the content of the processConditionalComments through minifier processing conditions. false

  • ProcessScripts handles the string array of script element types through minifier(for example, TEXT /ng-template, Text/X-handlebars-template, etc.). []

  • QuoteCharacter reference type used for attribute values (‘or’)

  • RemoveAttributeQuotes removes quotes if possible. false

  • RemoveComments with HTML comments false

  • RemoveEmptyAttributes Deletes all attributes, only whitespace-only values. false (could betrue,Function(attrName, tag))

  • RemoveEmptyElements removes all elements with empty content. false

  • RemoveOptionalTags removeOptionalTags false

  • RemoveRedundantAttributes duty match the default delete attributes. false

  • RemoveScriptTypeAttributes is removed from the script tag type = “text/javascript”. Other types of attribute values are complete. false

  • RemoveStyleLinkTypeAttributes is removed from the style and the link tag type = “text/CSS”. Other types of attribute values are complete. false

  • RemoveTagWhitespace removes as much space between attributes as possible. Note that this will result in invalid HTML! false

  • SortAttributes Sorts by frequency attributes False

  • SortClassName classifies style classes by frequency. false

  • TrimCustomFragments adjusts the white space around ignoreCustomFragments. false

  • UseShortDoctype Replaces docType with short (HTML5) doctype. false

chunks

Allow some chunks to be inserted into the template. If this is not configured, all thunk entries in the entry will be injected into the template by default

When configuring multiple pages, the thunk for each page should be different. You need to use this configuration to inject different Thunk for different pages

Chunks are basically the option to use js that you add to your page

plugins: [
    new httpWebpackPlugin({
    chunks: ['index','main']
    })
]
Copy the code

So after compiling:

<script type=text/javascript src="index.js"></script>
<script type=text/javascript src="main.js"></script>
Copy the code

ExcludeChunks: Excludes js that are used to configure thunk that does not allow injection

ChunksSortMode: none | auto | function, the default auto

Allows the specified thunk to sort before inserting it into an HTML document.

The function value can specify a collation

Auto Sorts packets based on thunk ids

None means not sort

Inject has four values: true body head false

Inject all static resources into template or templateContent. Different configuration values are injected at different locations

True default value or body, where all JavaScript resources are inserted at the bottom of the body element

The head Script tag is located in the head of an HTML file

False Does not insert the generated JS file, which is almost never used

favicon

Add a specific Favicon path to the output HTML document, which, like the title configuration item, needs to dynamically retrieve its path value in the template

The result is that the generated HTML file generates a Favicon with the value of a path: favicon: ‘path/to/my_favicon.ico’, which then has a link tag in the regenerated HTML

<link rel="shortcut icon" href="example.ico">
Copy the code

Cache: true | false and true by default

Generates a new file when the content changes

True means emit the file after the corresponding Thunk file is modified

Hash: Boolean value, false by default

Would you like to add the unique hash value generated by each compilation of webPack to all injected static resources as follows:

html <script type="text/javascript" src="common.js? a3e1396b501cdd9041be"></script>Copy the code

XHTML: true | false, false by default

Whether to render link as a self-closing label, and true as a self-closing label

ShowErrors: true | false, true by default

Whether to output error information to an HTML page

Configure multiple HTML page examples

There are three entry pages in the application: index. HTML, course. HTML and about. HTML. And the thunk injected varies from page to page;

For a multi-page application, configure one for each page.

// The __dirname directory is E:\MyLocalProject\webpackDemo const path = require('path') const htmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { general: './src/skin/general/js/general.js', index: './src/skin/index/js/index.js', course: './src/skin/course/js/index.js', about: './src/skin/about/js/index.js', }, output: { path: Path.resolve (__dirname, 'dist'), filename: 'skin/[name]/[name].js', // must be relative path publicPath: '.. /.. /'}, module: {rules: [// exclude: /(node_modules)/, loader: [// exclude: /(node_modules)/, loader: 'babel-loader'},]}, // plugins: new htmlWebpackPlugin({template: path.join(__dirname, '/src/static/index.html'), filename: 'static/index.html', minify: { collapseWhitespace: true }, hash: true, favicon: 'favicon.ico', chunks: ['general', 'index'] }), new htmlWebpackPlugin({ template: path.join(__dirname, '/src/static/course/index.html'), filename: 'static/course/index.html', minify: { collapseWhitespace: true, }, hash: true, favicon: 'favicon.ico', chunks: ['general', 'course'] }), new htmlWebpackPlugin({ template: path.join(__dirname, '/src/static/about/index.html'), filename: 'static/about/index.html', minify: { collapseWhitespace: true }, hash: true, chunks: ['general', 'about'], favicon: 'favicon.ico' }), ] }Copy the code

Project directory structure

Use gloB to scan paths and automatically configure HTML

// The __dirname directory is E: MyLocalProject webpackDemo const path = require('path') const htmlWebpackPlugin = Static glob = require('html-webpack-plugin') const glob = require("glob"); const staticHtmlPath = glob.sync('src/static/**/*.html'); Entrys const entrys = {}; // Set the public js entry file const commonJSObj = {general: '. / SRC/skin/general/js/general. Js',} Object. The assign (entrys, commonJSObj) / / define HTML - webpack - plugin configuration items const htmlCfgs = [];  const htmlCfgsObj = {}; Statichtmlpath.foreach ((filePath) => {let path = filepath.split ('/') let pathLength = path.length // get the filename let filename = path[pathLength-1].split('.')[0] // Dynamic configuration entry file path let entryJSName = path[pathLength-2] + '-' + filename entrys[entryJSName] = './src/skin/' + path[pathLength - 2] + '/js/' + filename + '.js'; New htmlWebpackPlugin({template: filePath, filename: filePath. Replace (' SRC ', ''), minify: { collapseWhitespace: true }, hash: true, favicon: 'favicon.ico', chunks: [entryJSName, 'general'], }) ) }); Module. exports = {devtool: 'inline-source-map', // entry: entrys, // export: {path: Path.resolve (__dirname, 'dist'), // must be absolute path filename: 'skin/[name]/[name].js', // must be relative path publicPath: '.. /.. / '}, / / development server devServer: {}, / / module configuration module: {rules: [/ / configure Babel, automatic compilation es6 grammar {test: / \. Js $/, exclude: /(node_modules)/, loader: 'babel-loader'},]}, // Plugins: htmlCfgs, // resolve: {}}Copy the code

Refer to the article: www.cnblogs.com/wonyun/p/60…