html-webpack-plugin
html-webpack-plugin 主要有两个作用:
- 可以生成创建html入口文件,比如单页面可以生成一个html文件入口,配置N个
html-webpack-plugin
可以生成N个页面入口 - 为
html
文件中引入的外部资源如script
、link
动态添加每次compile
后的hash
,防止引用缓存的外部文件问题
开始
- 安装
html-webpack-plugin
依赖
yarn add html-webpack-plugin -D
语法
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html',
title:'学习webpack'
}),
]
-
title: 生成的html文档的标题。配置该项,它并不会替换指定模板文件中的title元素的内容,除非html模板文件中使用了模板引擎语法来获取该配置项值。用法如下:
-
webpack.config.js
配置html-webpack-plugin
中的title
plugins:[
new HtmlWebpackPlugin({
title:"学习 Webpack",
template:Path.resolve(process.cwd(),'./public/index.html')
})
] -
public/index.html
模板文件使用模板引擎语法<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body></body>
</html>
-
-
filename: 输出文件的文件名称,默认为index.html,不配置就是该文件名
-
template: 本地模板文件的位置,支持加载器(如handlebars、ejs、undersore、html等)
-
injext: 向template或者templateContent中注入所有静态资源,不同的配置值注入的位置不经相同
- true或者body: 所有JavaScript资源插入到body元素的底部
- head: 所有JavaScript资源插入到head元素中
- false: 所有静态资源css和JavaScript都不会注入到模板文件中
-
favicon: 添加特定favicon路径到输出的html文档中,这个同title配置项,需要在模板中动态获取其路径值
-
hash: true|false,是否为所有注入的静态资源添加webpack每次编译产生的唯一hash值
-
chunks: 允许插入到模板中的一些chunk,不配置此项默认会将entry中所有的thunk注入到模板中。在配置多个页面时,每个页面注入的thunk应该是不相同的,需要通过该配置为不同页面注入不同的thunk;
-
minify: 压缩
html
模板new HtmlWebpackPlugin({
title: "学习 Webpack",
minify: {
removeComments: true, // 去除注释
collapseWhitespace: true, // 去除空格
},
template: Path.resolve(process.cwd(), "./public/index.html"),
}), -
excludeChunks: 这个与chunks配置项正好相反,用来配置不允许注入的thunk。
-
自定义配置项: 可以自行添加属性,通过
ejs
动态输出到html模板中