#image fallback in collection schema helper

3 messages · Page 1 of 1 (latest)

tacit citrusBOT
#

Hi @neat raft. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The issue you're experiencing might be related to the way Astro handles image imports during the build process. In the development mode, Astro can resolve relative paths to images, but during the build process, it might fail to do so.

In your case, you're trying to import an image directly in your config.ts file. This might not be the best approach, as the Astro build process might not be able to resolve the image path correctly.

Instead, you could consider defining the image path in the frontmatter of your content files. Astro provides a way to handle images in content collections. You can declare an associated image for a content collections entry, such as a blog post’s cover image, in your frontmatter using its path relative to the current folder. Here's an example:

---
title: "My first blog post"
cover: "./firstpostcover.jpeg" # will resolve to "src/content/blog/firstblogcover.jpeg"
coverAlt: "A photograph of a sunset behind a mountain range."
---
This is a blog post

Then, in your config.ts file, you can use the image helper from the content collections schema to validate the image metadata:

import { defineCollection, z } from "astro:content";

const blogCollection = defineCollection({
  schema: ({ image }) => z.object({
    title: z.string(),
    cover: image().refine((img) => img.width >= 1080, { message: "Cover image must be at least 1080 pixels wide!", }),
    coverAlt: z.string(),
  }),
});

export const collections = { blog: blogCollection, };

This way, Astro will be able to correctly resolve the image paths during the build process. If the image that you reference in your frontmatter doesn’t exist, Astro will let you know.