一、使用Webpack的url-loader
1. 安装url-loader
首先,确保你的项目中已经安装了Webpack。如果没有安装,可以通过以下命令进行安装:
npm install --save-dev url-loader file-loader
2. 配置Webpack
在Webpack的配置文件(通常是webpack.config.js
)中,添加以下配置:
module.exports = {
// ...其他配置
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10240, // 当图片小于10KB时,将其转换为Base
name: 'img/[name].[hash:7].[ext]', // 输出文件名和路径
},
},
],
},
],
},
};
3. 使用图片
<img src="/path/to/image" alt="描述">
二、使用Vue CLI的配置
1. 配置vue.config.js
在vue.config.js
文件中,添加以下配置:
module.exports = {
// ...其他配置
chainWebpack: config => {
config.module
.rule('images')
.use('url-loader')
.loader('url-loader')
.tap(options => Object.assign(options, { limit: 10240 }))
.end();
},
};
2. 使用图片
与Webpack配置相同,无需添加后缀:
<img src="/path/to/image" alt="描述">