How i am rendering images dynamically in astro components
import { Image } from "astro:assets";
import type { ImageMetadata } from "astro";
const images = import.meta.glob<{ default: ImageMetadata }>(
"/src/assets/*.{jpeg,jpg,png,gif,avif,jpg,svg,webp}"
);
const { title, description, resource } = Astro.props;
<Image
height={24}
width={24}
class="rounded-md"
src={images[resource]()}
alt={title}
/>
This works and compiles into - http://thundering-knowledge.surge.sh/_astro/default-img.DQCbfkMr_ZEy79V.webp in build
For my react component I had to do this tedious work around
src/assets/Images.jsx
const IMAGES = {
'/src/assets/default-img.webp' : new URL('./default-img.webp', import.meta.url).href,
'/src/assets/drone.png' : new URL('./drone.png', import.meta.url).href,
'/src/assets/ImageMetaGenerator.js' : new URL('./ImageMetaGenerator.js', import.meta.url).href,
'/src/assets/MdiAccessPointNetwork.svg' : new URL('./MdiAccessPointNetwork.svg', import.meta.url).href,
'/src/assets/MdiCog.svg' : new URL('./MdiCog.svg', import.meta.url).href,
'/src/assets/MdiEarth.svg' : new URL('./MdiEarth.svg', import.meta.url).href,
'/src/assets/MdiLightbulb.svg' : new URL('./MdiLightbulb.svg', import.meta.url).href
};
export default IMAGES;
for creating an index of the files and so that at build they are "noticed" so the image path can be updated
usage
import IMAGES from "@/assets/Images";
const ProductCard: React.FC<Props> = ({
title,
description,
resource,
href,
})
=> {
return (
<img
className="w-full h-auto"
width="1209"
height="890"
loading="lazy"
decoding="async"
alt=""
aria-hidden="true"
//@ts-ignore
src={IMAGES[resource]}
/>
)
}
This does not work and compiles into - http://thundering-knowledge.surge.sh/_astro/default-img.DQCbfkMr.webp
In both case resource being the image path i.e "/src/assets/img.webp"
astro.config.mjs
export default defineConfig({
integrations: [tailwind({
applyBaseStyles: false
}), react(), icon(), compress(), compressor()]
});
I feel like this has some thing to do with the astro plugins that are minifying the images used in astro components but not the one in the react components
I tried finding solutions for this but have had no luck so far
Any help is much appreciated , Thank you !