You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite+React+TailwindCSS项目部署Vercel后背景图无法加载求助

问题:Vite+React+TailwindCSS项目部署到Vercel后背景图片无法加载

本地运行一切正常,但部署到Vercel后唯独背景图片无法加载,相关信息如下:

  • 技术栈:Vite构建工具、React、TailwindCSS
  • 图片路径:./public/images/bg-mobile.svg
  • 已在tailwind.config.cjs中导入该图片并配置为Tailwind的背景类使用

配置文件代码

// tailwind.config.cjs
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {
      colors: {
        "huddle-violet": "hsl(257, 40%, 49%)",
        "huddle-magenta": "hsl(300, 69%, 71%)",
      },
      backgroundImage: {
        "desktop": "url('./images/bg-desktop.svg')",
        "mobile": "url('./images/bg-mobile.svg')"
      },
    },
  },
  plugins: [require('prettier-plugin-tailwindcss')],
};

HTML代码

// index.html
<body class="bg-huddle-violet bg-mobile bg-contain bg-no-repeat">
  <div id="root"></div>
  <script type="module" src="/src/main.tsx"></script>
</body>

解决方案

问题出在Tailwind配置里的图片路径写法。Vite构建时,public目录下的资源会被部署到站点根路径,相对路径在生产环境下会导致资源查找失败,需改用绝对路径。

修改tailwind.config.cjs中的backgroundImage配置:

backgroundImage: {
  "desktop": "url('/images/bg-desktop.svg')",
  "mobile": "url('/images/bg-mobile.svg')"
},

原理:本地开发时相对路径./images/...能被正确解析,但部署后浏览器会以当前页面路径为基准查找资源,绝对路径/images/...会直接从站点根目录加载图片,避免路径解析错误。

内容的提问来源于stack exchange,提问作者badmood111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:00:52