React中无需顶部import语句及public目录,加载src/images下图片的实现方法
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 yoursrc/imagesfolder, process it (optimize, hash the filename, etc.), and copy it to your build’s output directory.- The
.defaultsuffix is needed because when usingrequirewith ES modules (standard in React setups), the processed asset is exported under thedefaultproperty.
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

