【笔记】Webpack的HTMLWebpackPlugin插件

前言

Webpack通过HTMLWebpackPlugin插件实现生成HTML文件
自动向HTML文件中通过<script></script>标签引入JS文件
配合mini-css-extract-plugin可以自动向HTML文件中通过<link>标签引入CSS文件

下载依赖

1
npm install -D html-webpack-plugin

修改配置文件

title:指定站点标题
template:指定EJS模板
filename:指定输出的文件
inject:指定引入JS文件的位置
minify:指定是否压缩HTML文件

false:不压缩

cache:指定是否缓存,使用缓存时打包后的文件没发生改变不会重新打包

webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const HTMLWebpackPlugin = require("html-webpack-plugin");

module.exports = {
plugins: [
new HTMLWebpackPlugin({
title: "站点标题",
template: "./src/index.html",
filename: "index.html",
inject: "body",
minify: false,
cache: true
})
]
};

压缩HTML文件

collapseWhitespace:删除HTML中的空白字符
removeComments:删除HTML中的注释
removeEmptyAttributes:删除空属性,如:class=""
removeRedundantAttributes:删除多余的属性,如:<input type="text">删除type="text"属性
minifyJS:压缩HTML中的内联JS代码
minifyCSS:压缩HTML中的内联CSS代码

webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const HTMLWebpackPlugin = require("html-webpack-plugin");

module.exports = {
plugins: [
new HTMLWebpackPlugin({
minify: {
collapseWhitespace: true,
removeComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
minifyJS: true,
minifyCSS: true
}
})
]
};

完成