一、压缩体积
1、压缩js、css、html、图片
js、css、html、图片,都有插件可以压缩。 可用的插件有: js:terser-webpack-plugin css:optimize-css-assets-webpack-plugin html:html-webpack-plugin 图片:image-webpack-loader
安装好后的代码配置如下:
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin()
]
},
module: {
rules: [
{
oneOf: [
...
{
test: /\.(jpg|png|gif|bmp)$/,
use: [
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
},
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75
}
}
}
]
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
minify:{
collapseWhitespace:true,
removeComments:true
}
}),
new OptimizeCssAssetsWebpackPlugin()
]
}
2、清除无用的css
需要两个插件,purgecss-webpack-plugin和mini-css-extract-plugin,安装后代码如下:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PurgecssWebpackPlugin = require('purgecss-webpack-plugin');
const path = require('path');
const PATHS = {
src: path.resolve(__dirname, 'src')
}
module.exports = {
module: {
rules: [
{
oneOf: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'less-loader'
]
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css'
}),
new PurgecssWebpackPlugin({
paths: glob.sync(`${PATHS.src}/**/*`, {nodir: true})
})
]
}
|