Astroのコンテンツコレクションを使いこなす

Astro v5以降のContent Layer APIを使うと、Markdownファイルを型安全に管理できます。

基本的な設定

src/content.config.tssrc/直下)でコレクションのスキーマを定義します。

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

const blog = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "./src/content/blog" }),
  schema: z.object({
    title: z.string(),
    date: z.coerce.date(),
    description: z.string(),
  }),
});

export const collections = { blog };

glob ローダーで src/content/blog/ 以下のMarkdownファイルを自動的に収集します。

コレクションからデータを取得する

---
import { getCollection } from "astro:content";
const posts = await getCollection("blog");
---

zodによるスキーマ定義で、フロントマターの型がビルド時に検証されます。

記事IDについて

Astro v5以降のContent Layer APIでは、post.slugは廃止されpost.idを使います。post.idはファイル名から拡張子を除いた文字列(例: hello-world)になります。

<a href={`/blog/${post.id}`}>{post.data.title}</a>