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

Vite+React+react-lazy:相对图片路径在开发与构建阶段均失效

解决Vite+React中react-lazy-load-image-component相对图片路径失效问题

问题原因

Vite对静态资源的处理依赖显式的导入语法或new URL() API,直接传入字符串形式的相对路径时,Vite无法识别这是需要处理的静态资源:

  • 开发阶段:src/assets目录并非服务器根目录,直接访问/assets/xxx会返回404
  • 构建阶段:Vite会给src/assets下的资源添加hash后缀并调整输出路径,字符串路径无法匹配到最终的资源文件

解决方案

方案1:用new URL()动态生成资源路径(推荐,无需调整项目结构)

在ProjectCard.jsx中,通过new URL()将传入的相对路径转换为Vite可识别的资源URL:

const ProjectCard = ({
  // ... 其他props
  imgPath,
  placeholderPath,
  title
}) => {
  // 基于当前组件文件的URL,解析传入的相对图片路径
  const imgUrl = new URL(imgPath, import.meta.url).href;
  const placeholderUrl = new URL(placeholderPath, import.meta.url).href;

  return (
    <div className="project-card">
      {/* 其他代码 */}
      <LazyLoadImage
        className="project-img"
        src={imgUrl}
        alt={title}
        placeholderSrc={placeholderUrl}
        effect="opacity"
      />
      {/* 其他代码 */}
    </div>
  );
};

export default React.memo(ProjectCard);

在ProjectSection.jsx中,传入相对于ProjectCard.jsx的路径即可:

<ProjectCard
  imgPath="../../assets/images/projects/presto_store.jpg"
  placeholderPath="../../assets/images/projects/presto_store-compressed.jpg"
  title="Presto Store"
  // ... 其他props
/>

方案2:批量导入项目图片(适合图片数量固定的场景)

在ProjectSection.jsx中用import.meta.glob批量导入所有项目图片,再将处理后的URL传给子组件:

// 批量导入src/assets/images/projects下的所有jpg图片,eager设为true立即加载
const projectImages = import.meta.glob('../../assets/images/projects/*.jpg', { eager: true });

// 渲染ProjectCard时传入对应的图片URL
<ProjectCard
  imgPath={projectImages['../../assets/images/projects/presto_store.jpg'].default}
  placeholderPath={projectImages['../../assets/images/projects/presto_store-compressed.jpg'].default}
  title="Presto Store"
  // ... 其他props
/>

这种方式和你在AboutMeSection.jsx中用import导入图片的逻辑一致,Vite会自动处理路径和资源优化。

方案3:将图片移至public目录(不推荐,无Vite资源优化)

把src/assets/images/projects下的图片移动到public/assets/images/projects目录,之后直接使用绝对路径:

<ProjectCard
  imgPath="/assets/images/projects/presto_store.jpg"
  placeholderPath="/assets/images/projects/presto_store-compressed.jpg"
  title="Presto Store"
  // ... 其他props
/>

⚠️ 注意:public目录下的资源不会被Vite处理(无hash后缀、无自动压缩),可能存在缓存问题,仅适合无需优化的静态资源。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:25:40