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

React.js映射循环中引入本地图片失败问题求助

Why require() Fails in map() Loops with Create React App?

Great question! Let's break down exactly why this is happening and walk through a few solid solutions.

The Root Cause: Webpack's Static Resource Resolution

Create React App uses Webpack under the hood, and Webpack relies on static analysis during the build process to find and bundle assets like images. When you use require('../images/dragonglass_pendant.jpg') directly (outside a loop), Webpack sees the static string path and can immediately locate the image, process it, and include it in your build.

But when you pass a dynamic variable like imageSrc to require() inside a map() loop, Webpack can't predict what that variable will be at build time. It has no way to scan all possible paths the variable might hold, so it throws the "Cannot find module" error—it literally can't resolve the path during the build.


Solution 1: Pre-Load All Images (Best for Known Image Lists)

If you know all the images you need upfront (like your example), pre-load each one with require() first, then loop through the pre-loaded paths. This lets Webpack resolve every image during the build:

const ThumbNail = styled.img` border: 2px dotted blue; `;
export default props => {
  // Pre-load images with static require calls
  const images = [
    require('../images/dragonglass_pendant.jpg'),
    require('../images/dragonglass_pendant2.jpg'),
    require('../images/dragonglass_pendant3.jpg'),
  ];
  return (
    <React.Fragment>
      { images.map((imageSrc, index) => {
          console.log(imageSrc, `=====imageSrc=====`);
          return <ThumbNail key={index} src={imageSrc} />
        }) }
    </React.Fragment>
  )
}

Solution 2: Use the public Folder (Best for Dynamic/API-Driven Images)

If you need to load images based on dynamic data (like API responses), move your images to the public/images folder in your project root. Files in public aren't processed by Webpack—they're copied directly to your build folder, so you can reference them with absolute paths:

const ThumbNail = styled.img` border: 2px dotted blue; `;
export default props => {
  // Example: Filenames from an API response
  const imageFilenames = [
    'dragonglass_pendant.jpg',
    'dragonglass_pendant2.jpg',
    'dragonglass_pendant3.jpg',
  ];
  return (
    <React.Fragment>
      { imageFilenames.map((filename, index) => {
          // Use process.env.PUBLIC_URL to avoid path issues
          const imageSrc = `${process.env.PUBLIC_URL}/images/${filename}`;
          console.log(imageSrc, `=====imageSrc=====`);
          return <ThumbNail key={index} src={imageSrc} />
        }) }
    </React.Fragment>
  )
}

Note: Make sure the filenames match exactly, and don't use require() or import for images in the public folder.

Solution 3: Batch Import with require.context (Best for Large Image Sets)

If you have a lot of images in one directory, use Webpack's require.context to load all of them at once. This lets you dynamically access images without writing individual require() calls:

const ThumbNail = styled.img` border: 2px dotted blue; `;
// Create a context to load all .jpg files in ../images
const imageContext = require.context('../images', false, /\.jpg$/);

export default props => {
  // Get all image paths from the context
  const imagePaths = imageContext.keys();
  return (
    <React.Fragment>
      { imagePaths.map((path, index) => {
          // Use the context to load the image
          const imageSrc = imageContext(path);
          console.log(imageSrc, `=====imageSrc=====`);
          return <ThumbNail key={index} src={imageSrc} />
        }) }
    </React.Fragment>
  )
}

Webpack scans the specified directory during the build, so it knows all the images to bundle—even when you access them dynamically.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:23:37