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

Create React App项目中动态引入图片路径报错求助

解决create-react-app中动态引入图片路径的问题

我之前也碰到过一模一样的情况!在create-react-app项目里,静态写死路径用require没问题,但用变量动态引入就报错,核心原因是webpack的静态编译机制——它需要在编译阶段明确知道要打包的文件路径,而动态字符串变量没法被它提前解析,所以才会抛出“找不到模块”的错误。

下面给你两个实用的解决办法:

方法一:提前在数据中处理require

直接在你的数据数组里,把图片路径换成require的结果,这样webpack编译时就能识别到每个图片并打包:

const data = [
  { 
    image: require(`./../../../assets/icons/1458.svg`), 
    title: 'title1', 
    description: 'description1' 
  },
  { 
    image: require(`./../../../assets/icons/48754.svg`), 
    title: 'title2', 
    description: 'description2' 
  },
  { 
    image: require(`./../../../assets/icons/7548.svg`), 
    title: 'title3', 
    description: 'description3' 
  }
];

之后在组件里直接使用image属性即可,不用再嵌套require:

const Info = ({ image, title, description }) => {
  return (
    <div>
      <img src={image} />
      <h1>{title}</h1>
      <p>{description}</p>
    </div>
  );
};

方法二:使用require.context预加载图片

如果你的图片数量很多,或者需要保留字符串路径的灵活性,可以用webpack的require.context来批量预加载指定目录下的图片,然后通过路径匹配获取资源:

首先,在组件中创建一个上下文,指定图片所在的目录、是否递归查找、匹配的文件后缀:

const Info = ({ image, title, description }) => {
  // 创建上下文:第一个参数是图片目录,第二个false表示不递归子目录,第三个是匹配svg文件的正则
  const iconsContext = require.context('./../../../assets/icons', false, /\.svg$/);
  
  // 注意:这里的image要对应上下文目录下的文件名,所以可以把data里的路径简化成文件名(比如'1458.svg')
  const imageUrl = iconsContext(`./${image}`);

  return (
    <div>
      <img src={imageUrl} />
      <h1>{title}</h1>
      <p>{description}</p>
    </div>
  );
};

对应的data数组可以简化为:

const data = [
  { 
    image: '1458.svg', 
    title: 'title1', 
    description: 'description1' 
  },
  { 
    image: '48754.svg', 
    title: 'title2', 
    description: 'description2' 
  },
  { 
    image: '7548.svg', 
    title: 'title3', 
    description: 'description3' 
  }
];

这两种方法都能解决动态引入的问题,方法一更适合数据固定的场景,方法二更适合图片量大或者需要动态生成路径的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:05:53