vue2项目webpack4.46.0使用 image-webpack-loader
时间: 2023-08-16 18:14:54 浏览: 157
在 Vue2 项目中使用 image-webpack-loader 需要进行以下步骤:
1. 安装 image-webpack-loader:
```
npm install --save-dev image-webpack-loader
```
2. 在 webpack 配置文件中添加 loader:
```
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/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.90],
speed: 4
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75
}
}
},
],
},
],
},
};
```
3. 在 Vue 组件中引用图片:
```
<template>
<div>
<img :src="require('@/assets/images/logo.png')" alt="Logo">
</div>
</template>
```
注意:如果使用了 vue-cli 创建的项目,需要在 `vue.config.js` 中配置 webpack:
```
module.exports = {
chainWebpack: config => {
config.module
.rule('images')
.test(/\.(png|jpe?g|gif|svg)$/i)
.use('file-loader')
.loader('file-loader')
.tap(options => {
// 修改选项
options.name = '[name].[ext]';
options.outputPath = 'images/';
return options;
})
.end()
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
mozjpeg: {
progressive: true,
quality: 65
},
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75
}
})
.end();
}
};
```
阅读全文