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

React中无需顶部import语句及public目录,加载src/images下图片的实现方法

How to render images from src/images without top-level imports or public folder in React

Hey there! The problem with your current code is that using a raw string path like "./images/star1.png" doesn’t let your bundler (usually webpack) recognize the image as a resource to process. When you build your app, the image won’t be copied to the output directory, and the browser will end up looking for a file that doesn’t exist at that path.

Here’s a simple fix that avoids top-level imports and the public folder—we’ll use require() to dynamically resolve the image path, which tells webpack to handle the asset properly:

import React from "react"
import ReactDOM from "react-dom"

class App extends React.Component {
  render(){
    // Use require to let webpack resolve and process the image
    let starIcon = require("./images/star1.png").default;
    return(
      <>
        <h1>Hello</h1>
        <img src={starIcon} alt="Star icon" /> {/* Added alt text for accessibility! */}
      </>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"))

Why this works:

  • require("./images/star1.png") signals to webpack to locate the image in your src/images folder, process it (optimize, hash the filename, etc.), and copy it to your build’s output directory.
  • The .default suffix is needed because when using require with ES modules (standard in React setups), the processed asset is exported under the default property.

Just a quick check: make sure your project’s bundler config (like Create React App’s built-in webpack setup) supports image assets—most modern React starters already include loaders like asset-module or file-loader to handle this automatically, so you shouldn’t need extra configuration.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:57:50