Skip to content

Instantly share code, notes, and snippets.

@11Firefox11
Last active May 12, 2023 16:00
Show Gist options
  • Save 11Firefox11/817beec030bc911bad8c39816cde6d1e to your computer and use it in GitHub Desktop.
Save 11Firefox11/817beec030bc911bad8c39816cde6d1e to your computer and use it in GitHub Desktop.
CleverImage Astro component for my responsive images
---
import { ImageGenerator } from "ImageGenerator";
interface Props {
imgPath: string,
alt: string,
sizes: { width: number; height: number }[],
withWebp?: boolean,
loading?: "eager" | "lazy" | null,
breakpoints?: {maxWidth: number, imgWidth: number}[]
}
const { imgPath, alt, sizes, withWebp, loading, breakpoints } = Astro.props;
const biggestSize = sizes.reduce((prev, current) => {return (prev.width > current.width) ? prev : current;});
const generatedSrcset: string[] = [];
const generatedSizes: string[] = [];
if (import.meta.env.PROD) {
let allBreakpointSizes: number[] | null = null;
if (breakpoints) {
allBreakpointSizes = breakpoints.map(bp => bp.imgWidth);
}
sizes.sort((a, b) => a.width - b.width);
for (const size of sizes) {
if (allBreakpointSizes && allBreakpointSizes.indexOf(size.width) === -1) {continue;}
((withWebp ?? true) ? [true, false] : [false]).forEach((isWebp) => {
generatedSrcset.push(`${ImageGenerator.generateName(imgPath, size, isWebp)} ${size.width}w`);
});
}
if (breakpoints) {
for (const breakpoint of breakpoints) {
if (breakpoint.maxWidth === 0) {
generatedSizes.push(`${breakpoint.imgWidth}px`);
} else {
generatedSizes.push(`(max-width: ${breakpoint.maxWidth}px) ${breakpoint.imgWidth}px`);
}
}
}
}
---
{import.meta.env.PROD && (
<img
src={ImageCompressorIntegration.generateName(imgPath, biggestSize)}
alt={alt}
srcset={generatedSrcset.join(", ")}
sizes={generatedSizes.join(", ")}
loading={loading}
/>
)
}
{import.meta.env.DEV && <img src={imgPath} alt={alt} loading={loading} />}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment