React项目localhost图片不显示求助(已用require()方法)
React项目本地服务器图片加载失败问题解决
问题原因
直接使用字符串路径引用图片时,VS Code能识别本地文件路径所以显示正常,但Webpack打包时不会处理纯字符串路径,导致图片未被复制到构建后的输出目录,localhost服务器找不到对应资源返回404错误。
解决方案
提供两种可行修复方案,按需选择:
方案1:通过require()正确引用图片(推荐)
修改data/data.js,将图片路径改为require()导入形式,Webpack会自动处理图片资源,打包时复制到输出目录并生成正确路径:
export const dataJson = [ { id: 1, name: "forest_walk_dabiediedu_winter.jpg", src: require("../images/forest_walk_dabiediedu_winter.jpg"), explanation: "dabie is one of the craziest creatures i've ever created. " + "His ambition to find the infinity stones will lead him to the " + "his lost family.", alt: "my monster dabie in snow" }, // 其他图片对象按相同方式修改 ];
组件中无需额外改动,直接使用props.src即可。
方案2:将图片移到public目录(适合多静态资源场景)
若项目基于Create React App创建,默认存在public目录,将images文件夹整体移到public下,再修改data.js中的路径为根相对路径:
export const dataJson = [ { id: 1, name: "forest_walk_dabiediedu_winter.jpg", src: "/images/forest_walk_dabiediedu_winter.jpg", explanation: "dabie is one of the craziest creatures i've ever created. " + "His ambition to find the infinity stones will lead him to the " + "his lost family.", alt: "my monster dabie in snow" }, // 其他图片对象按相同方式修改 ];
Webpack会直接将public目录下的资源复制到构建后的根目录,可通过/images/xxx.jpg直接访问。
验证修改
修改完成后重启本地开发服务器,图片即可正常加载。若仍有问题,检查:
require()路径是否正确(相对于data.js的位置)- 图片文件名是否与代码一致(服务器环境区分大小写)
内容的提问来源于stack exchange,提问作者EcolePrusienne
相关产品推荐
相关产品推荐

