React.js + Vite环境下如何遍历映射文件夹中的所有图片?
解决React中遍历public目录图片时
require is not defined的问题 错误原因
require.context是Webpack提供的模块遍历功能,仅能处理src目录内被Webpack打包的资源。而public目录下的文件会被直接复制到构建产物中,不经过Webpack解析,因此这里使用require会触发未定义错误,且这种方式本身也无法遍历public里的图片。
解决方案
方案1:直接访问public目录下的图片(手动维护文件名)
public目录的图片可通过绝对路径直接访问,若图片数量不多,可手动维护文件名列表:
// 假设public/_fairImages下的图片为img1.jpg、img2.png等 const imageNames = ['img1.jpg', 'img2.png', 'img3.jpeg']; function GalleryPage() { return ( <div className="galleryPage_v2"> <div className="galleryWrapper"> {imageNames.map((name, index) => ( <img src={`/_fairImages/${name}`} alt={`画廊图片 ${index + 1}`} className="galleryImg" key={index} /> ))} </div> </div> ); }
方案2:自动遍历图片(将图片移至src目录)
若需要自动遍历无需手动维护文件名,需将图片移到src目录下(比如src/assets/_fairImages),再根据项目构建工具选择对应方法:
若使用Create React App(Webpack)
// 图片移至src/assets/_fairImages后 const images = require.context('../assets/_fairImages', true, /\.(png|jpe?g|svg)$/); const imageList = images.keys().map(image => images(image)); function GalleryPage() { return ( <div className="galleryPage_v2"> <div className="galleryWrapper"> {imageList.map((image, index) => ( <img src={image.default} alt={`画廊图片 ${index + 1}`} className="galleryImg" key={index} /> ))} </div> </div> ); }
若使用Vite
Vite不支持require.context,需用import.meta.glob:
// 图片移至src/assets/_fairImages后 const imageModules = import.meta.glob('../assets/_fairImages/*', { eager: true }); const imageList = Object.values(imageModules).map(module => module.default); function GalleryPage() { return ( <div className="galleryPage_v2"> <div className="galleryWrapper"> {imageList.map((image, index) => ( <img src={image} alt={`画廊图片 ${index + 1}`} className="galleryImg" key={index} /> ))} </div> </div> ); }
内容的提问来源于stack exchange,提问作者Martin Arreola
相关产品推荐
相关产品推荐

