安装依赖cnpm install --save-dev image-webpack-loader
配置,如果不是vue-cli3.x就在 webpack.base.confi.js中配置
在 webpack.base.confi.js 文件中进行配置
这里有两点需要注意的地方:
- url-loader 和 image-webpack-loader 不能一起使用,否则会导致图片出不来
- 一定要先写 ‘file-loader’ 才能使用 ‘image-webpack-loader’
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash:7].[ext]',
outputPath: 'mobile/img'
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 50
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false,
},
pngquant: {
quality: [0.5, 0.65],
speed: 4
},
gifsicle: {
interlaced: false,
},
//ios不支持
// webp: {
// quality: 100
// }
}
}
]
}
...
]
}
如果是在vue-cli3及更高版本中没有webpack.base.confi.js文件的话,在vue.config.js文件中配置
module.exports ={
...
chainWebpack(config){
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
bypassOnDebug: true
})
.end()
}
}
注意:如果是使用已经压缩过的图片,再使用这个依赖进行压缩可能导致图片文件更大,亲测使用熊猫压缩后图片0.89M,再将图片放入项目进行打包压缩后,图片变成了0.98M