使用webpack4配置图片压缩
时间: 2023-12-10 19:05:09 浏览: 86
可以使用`image-webpack-loader`来实现图片压缩。下面是一个简单的webpack4配置示例:
1. 安装依赖:
```
npm install image-webpack-loader --save-dev
npm install imagemin --save-dev
npm install imagemin-pngquant --save-dev
npm install imagemin-mozjpeg --save-dev
```
2. 在webpack配置文件中添加以下代码:
```javascript
const path = require('path');
const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');
module.exports = {
// ...
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65
},
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.9],
speed: 4
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75
}
}
}
],
},
],
},
// ...
plugins: [
new ImageMinimizerPlugin({
minimizerOptions: {
plugins: [
imageminMozjpeg({
quality: 75,
progressive: true
}),
imageminPngquant({
quality: [0.6, 0.8]
})
]
}
})
]
}
```
其中,`image-webpack-loader`用于在打包时对图片进行压缩处理,`imagemin`用于在打包完成后对图片进行二次压缩处理。以上是一个简单的配置示例,根据具体情况可以进行适当的修改。
阅读全文