webpack如何压缩图片,请写一下配置
时间: 2023-06-24 11:08:56 浏览: 188
Webpack可以使用插件来压缩图片,最常用的插件是`image-webpack-loader`和`imagemin-webpack-plugin`。下面是一个简单的示例配置:
```javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist')
},
optimization: {
minimizer: [
new OptimizeCSSAssetsPlugin(),
new UglifyJsPlugin()
]
},
module: {
rules: [
{
test: /\.(png|jpg|jpeg|gif|svg)$/i,
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65
},
optipng: {
enabled: false,
},
pngquant: {
quality: '65-90',
speed: 4
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75
}
},
},
],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
}),
new ImageminPlugin({
pngquant: {
quality: '65-90'
}
})
]
};
```
其中,`image-webpack-loader`在处理图片文件时使用了一些其他优化工具(如`mozjpeg`、`pngquant`、`gifsicle`等),而`imagemin-webpack-plugin`则可以对压缩后的图片再进行一些优化。这样配置后,Webpack在打包时会自动将图片文件进行压缩和优化。
阅读全文