Skip to content

Instantly share code, notes, and snippets.

@Princesseuh
Last active January 30, 2022 04:13
Show Gist options
  • Save Princesseuh/43e3fde64bff62a469c96810d02e0623 to your computer and use it in GitHub Desktop.
Save Princesseuh/43e3fde64bff62a469c96810d02e0623 to your computer and use it in GitHub Desktop.
Astro + eleventy-img
---
import Image from "@11ty/eleventy-img"
import { generateImage } from "utils.ts"
import { Markdown } from "astro/components"
const {
src,
alt,
caption,
options = {},
sizes = "",
classes = undefined,
quality = 90,
} = Astro.props
const { url } = Astro.request
const image = generateImage(
// If our URL starts with a slash, let's assume the user know what they're doing and not alter the URL apart from the content prefix
src.startsWith("/") ? "src/content" + src : "src/content" + url.pathname + "/" + src,
Object.assign(options, {
widths: [null],
formats: ["avif", "webp", "png"],
sharpWebpOptions: {
quality: quality,
},
sharpAvifOptions: {
quality: quality,
},
}),
false,
)
const imageAttributes = {
alt: alt,
sizes: sizes,
loading: "lazy",
decoding: "async",
}
const html = Image.generateHTML(image, imageAttributes)
const props: Record<string, string> = {}
props.class ??= classes
---
<figure {...props}>
{html}
{caption && (
<figcaption>
<Markdown>{caption}</Markdown>
</figcaption>
)}
</figure>
import Image from "@11ty/eleventy-img"
export function generateImage(
src: string,
options,
addBasePath = true,
): Record<string, ImageFormat[]> {
const settings = Object.assign(options, {
outputDir: "public/assets/images",
urlPath: "/assets/images",
})
src = (addBasePath ? "src/assets" : "") + src
;(async () => {
await Image(src, settings)
})()
return Image.statsSync(src, settings)
}
export interface ImageFormat {
format: string
width: number
height: number
filename: string
outputPath: string
url: string
sourceType: string
srcset: string
size: number
}
@bronze
Copy link

bronze commented Jan 12, 2022

yuuup i screwed up. the code works beautifully! thank you @Princesseuh !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment