手动压缩图片
图片压缩是很重要的前端优化,一般可以选择手动压缩
手动压缩网站
webpack压缩图片
这里记录借助webpack
的image-webpack-loader
实现自动压缩图片
项目是create-react-app
搭建的,webpack@5.64.4
1、安装相应loader
npm i image-webpack-loader --save-dev
2、webpack相关配置
webpack@5.x
const imageInlineSizeLimit = parseInt(process.env.IMAGE_INLINE_SIZE_LIMIT || '10000');
{test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],type: 'asset',parser: {dataUrlCondition: {maxSize: imageInlineSizeLimit,},},use: [{loader: 'image-webpack-loader',options: {mozjpeg: {progressive: true,quality: 50},optipng: {enabled: false,},pngquant: {quality: [0.5, 0.65],speed: 4},gifsicle: {interlaced: false,},//ios不支持// webp: {// quality: 100// }}}],},
Webpack5 已经将file-loader
和url-loader
两个 Loader
功能内置到 Webpack
里了,所以只需要配置 type: "asset"
即可处理图片资源
webpack@4.x
webpack4
需要配置file-loader
{test: /\.(gif|png|jpe?g|svg)$/i,use: [{loader: "file-loader",options: {name: "[name].[hash:7].[ext]",outputPath: "img",},},{loader: "image-webpack-loader",options: {mozjpeg: {progressive: true, quality: 60, // JPG 输出的质量 一般60为可接受的},optipng: {enabled: true,},pngquant: {quality: [0.5, 0.65], // PNG 质量范围speed: 4,},gifsicle: {interlaced: false,// 优化GIF},webp: {quality: 75, // 转换为 webp},},},],},
实践踩坑
我的项目是webpack@5.x,node@14.19.1,npm安装image-webpack-loader
后一直报错
解决方法:切换node版本node@16.14.2
,删除image-webpack-loader
后重新安装
效果
使用前 0.99 MB
使用后 205 KB