Skip to content

Instantly share code, notes, and snippets.

@ivanmercedes
Created April 17, 2025 20:41
Show Gist options
  • Select an option

  • Save ivanmercedes/8f89cb3e5bffc1e5c683763b7fb68736 to your computer and use it in GitHub Desktop.

Select an option

Save ivanmercedes/8f89cb3e5bffc1e5c683763b7fb68736 to your computer and use it in GitHub Desktop.
---
import { getImage } from "astro:assets";
const { imageUrl, alt = "" } = Astro.props;
const imageImports = import.meta.glob("../assets/**/*.{png,jpg,jpeg,webp}", {
eager: true,
});
interface ImageModule {
default: ImageMetadata;
}
const images = Object.entries(imageImports).reduce(
(acc, [path, mod]) => {
const cleanPath = path.replace("../assets", "").replace(/\/+/g, "/");
acc[cleanPath] = (mod as ImageModule).default;
return acc;
},
{} as Record<string, ImageMetadata>
);
const image = images[imageUrl];
const optimizedImage = image
? await getImage({ src: image, width: 440, height: 250 })
: null;
---
{
optimizedImage && (
<img
src={optimizedImage.src}
alt={alt}
width={optimizedImage.options.width}
height={optimizedImage.options.height}
loading="lazy"
decoding="async"
class="h-60 object-cover"
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment