一、问题分析
- 打包后路径问题:Webpack打包时,会根据配置的
publicPath
来修改资源路径,如果配置不正确,会导致图片路径错误。 - 相对路径引用:在CSS中使用相对路径引用图片时,可能会因为打包后的文件结构改变而导致路径错误。
- CSS预处理器:使用Sass、Less等CSS预处理器时,需要注意图片路径的处理。
二、解决技巧
1. 修改Webpack配置
修改Webpack配置文件,设置正确的publicPath
和output.publicPath
,确保资源路径正确。
// webpack.config.js
module.exports = {
// ...
output: {
// ...
publicPath: '/static/', // 根据实际情况修改
},
// ...
};
2. 使用绝对路径
background: url('/static/images/logo.png') no-repeat;
3. 使用~
语法
在CSS中使用~
语法引用Vue组件中的静态资源,可以自动处理路径。
background: url(~@/static/images/logo.png) no-repeat;
4. 使用require
语法
background: url(require('@/static/images/logo.png')) no-repeat;
5. 修改Webpack插件配置
如果使用ExtractTextPlugin
等插件,需要修改其配置,确保资源路径正确。
// webpack.prod.conf.js
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
// ...
plugins: [
// ...
new ExtractTextPlugin({
filename: 'styles/[name].[contenthash].css',
publicPath: '/static/', // 根据实际情况修改
}),
],
};
三、实例分析
<template>
<div class="logo">
<img src="/static/images/logo.png" alt="Logo">
</div>
</template>
<script>
export default {
// ...
};
</script>
<style scoped>
.logo img {
width: 100px;
height: 100px;
background: url(~@/static/images/logo.png) no-repeat;
}
</style>