使用styled-components引入图片报错
前提 : 图片路径真实存在图片
- 场景一
直接以css方式引入背景图片
此时报错import styled from 'styled-components' export const LoginWrapper = styled.div` width: 100%; height: 100%; background: url('../../assets/images/timg.jpg') center no-repeat; background-image: 100% 100%; `
404
找不到
- 场景二
使用别名绝对路径引入图片 , 将图片作为变量引入
此时依旧报错import styled from 'styled-components' import img from '@/assets/images/timer.jpg' export const LoginWrapper = styled.div` width: 100%; height: 100%; background: url(${img}) center no-repeat; background-image: 100% 100%; `
404
找不到 , 但是路径换成了磁盘根路径
- 最终解决方案
使用相对路径引入图片 , 将图片作为变量引入import styled from 'styled-components' import img from '../../assets/images/timg.jpg' export const LoginWrapper = styled.div` width: 100%; height: 100%; background: url(${img}) center no-repeat; background-image: 100% 100%; `
此时图片正确引入
react项目使用vite 搭建 ,考虑可能是vite打包图片路径解析问题 ,如有必要可使用其他脚手架尝试
其余脚手架创建如未遇到此情况请忽略此问题