styled-components引入图片报错

使用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找不到 , 但是路径换成了磁盘根路径
    ![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2d7d0ec46ef233bfb5aad03e2222515c.png
  • 最终解决方案
    使用相对路径引入图片 , 将图片作为变量引入
    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打包图片路径解析问题 ,如有必要可使用其他脚手架尝试
其余脚手架创建如未遇到此情况请忽略此问题

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.温m_

如果喜欢可以支持打赏小哥!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值