webpack插件之HtmlWebpackPlugin

功能

htm-webpack-plugin插件的作用:
1)为html文件引入外部资源如script, link动态添加每次compile的Hash,防止引用缓存的外部文件问题。
2)可以生成创建html入口文件,比如单页面可以生成一个html文件入口,配置N个html-webpack-plugin可以生成N个页面入口。

安装

npm i html-webpack-plugin -D

配置

在webpack.config.js中

const HtmlWebpackPlugin = require('html-webpack-plugin')
...
plugins: [
	new HtmlWebpackPlugin({
		template: 'index.html'
	    filename: 'index.html',
	    hash: false,
	    inject: true,
	    compile: true,
	    favicon: false,
	    minify: false,
	    cache: true,
	    showErrors: true,
	    chunks: 'all',
	    excludeChunks: [],
	    title: 'Webpack App',
	    xhtml: false
	})
]

配置项

1) template

template: 本地模板文件的位置

注意:
1、template配置项在html文件使用file-loader时,其所指定的位置找不到,导致生成的html文件内容不是期望的内容。
2、为template指定的模板文件没有指定任何loader的话,默认使用ejs-loader。如template: './index.html',若没有为.html指定任何loader就使用ejs-loader

2) filename

filename: 生成的模板文件的名字

1、filename配置的html文件目录是相对于webpackConfig.output.path路径而言的,不是相对于当前项目目录结构的。
2、指定生成的html文件内容中的link和script路径是相对于生成目录下的,写路径的时候请写生成目录下的相对路径。

3) title

title: 生成的HTML模板的title,如果模板中有设置title的名字,则会忽略这里的设置。

4) inject

inject: 引入模块的注入位置;取值有true/false/body/head;true | ‘head’ | ‘body’ | false

1、true或者body:所有JavaScript资源插入到body元素的底部
2、head: 所有JavaScript资源插入到head元素中
3、false: 所有静态资源css和JavaScript都不会注入到模板文件中

5) favicon

favicon: 指定页面图标

6) minify

minify: {} | false , 传递 html-minifier 选项给 minify 输出。

   caseSensitive: false, //是否大小写敏感
   collapseBooleanAttributes: true, //是否简写boolean格式的属性如:disabled="disabled" 简写为disabled 
   collapseWhitespace: true //是否去除空格

7) hash

hash: 是否生成hash添加在引入文件地址的末尾,类似于我们常用的时间戳,比如最终引入是:<script type=“text/javascript” src=“bundle.049424f7d7ea5fa50656.js?049424f7d7ea5fa50656”>。这个可以避免缓存带来的麻烦

8) cache

cache: 是否需要缓存,如果填写true,则文件只有在改变时才会重新生成

9) showErrors

showErrors: 是否将错误信息写在页面里,默认true,出现错误信息则会包裹在一个pre标签内添加到页面上

10) chunks

chunks: 引入的模块,这里指定的是entry中设置多个js时,在这里指定引入的js,如果不设置则默认全部引入.

11) excludeChunks

excludeChunks: 排除的模块

12) xhtml

xhtml: 生成的模板文档中标签是否自动关闭,针对xhtml的语法,会要求标签都关闭,默认false

猜你喜欢

转载自blog.csdn.net/qq_29055201/article/details/88656943