注意import.meta.glob中定义的文件夹路径,视情况而定,可能是assets或images
import { useMemo } from "react";
export default function useImages() {
// 扫描 images 目录及其子目录下的所有图片
const modules = import.meta.glob('@/assets/**/*.{png,jpg,jpeg,svg}', { eager: true });
const images = useMemo(() => {
const map = {};
Object.entries(modules).forEach(([path, mod]) => {
// 提取相对路径,例如 icons/icon1.png
const relativePath = path.split('/images/')[1];
map[relativePath] = mod.default;
});
return map;
}, [modules]);
return images;
}
使用方法:
import useImages from "@/hooks/useImages";
const uimages = useImages()
<div style={{ backgroundImage: "url(" + uimages['bgred.png'] + ")" }}>
<img src={uimages['recommed.png']} className="w-7 ml-[10px]" />
例子:
