压缩html和js
1. js压缩
生产环境下会自动压缩js代码,所以js压缩只需要将配置文件中的mode设置为production即可
1.1 配置文件
const {
resolve
} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/built.js',
path: resolve(__dirname, 'build')
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
// 生产环境下会自动压缩js代码
mode: 'production'
}
1.2 运行webpack,查看构建结果
可以看到js代码都被压缩至一行
2. html压缩
html不需要进行兼容性处理,只需要压缩
html压缩通过HtmlWebpackPlugin实现
2.1 配置文件
const {
resolve
} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/built.js',
path: resolve(__dirname, 'build')
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
// 压缩html代码
minify: {
// 移除空格
collapseWhitespace: true,
// 移除注释
removeComments: true
}
})
],
// 生产环境下会自动压缩js代码
mode: 'production'
}
2.2 index.html源代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 只是一个注释 -->
<h1>hello webpack</h1>
</body>
</html>
2.3 运行webpack,查看构建结果
可以看到构建好的index.html被压缩至一行,注释也被移除