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

Ive put the image.astro inside component and the utils.ts under src, did i miss something?

Unable to render Image!

There are no `renderers` set in your `astro.config.mjs` file.
Did you mean to enable `@astrojs/renderer-react`, `@astrojs/renderer-preact`, `@astrojs/renderer-vue` or `@astrojs/renderer-svelte`?

Error: Unable to render Image!

@Princesseuh
Copy link
Author

Princesseuh commented Jan 12, 2022

@bronze I believe you might be missing the @11ty/eleventy-img dependency?

If that ain't it then I'm not too sure, this snippet is copied from my own website where it works. I'd have to see your complete setup to debug more, if you can make a reproduction on Stackblitz or other services that'd be nice (or send the repo where it happens)

@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