AstroのContent Collectionsを使ってみた
Astro v2から登場した Content Collections は、MarkdownやMDXファイルをZodスキーマで型安全に管理できる機能です。今回はその設定方法と使い方を整理してみました。
Content Collectionsとは
src/content/ ディレクトリ以下にファイルを置き、config.ts でスキーマを定義します。frontmatterのバリデーションが自動で行われ、TypeScriptの補完も効くようになります。
セットアップ
まず src/content/config.ts にコレクションを定義します。
import { defineCollection, z } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
}),
});
export const collections = { blog };
記事の取得
ページ側では getCollection を使って記事一覧を取得できます。
import { getCollection } from 'astro:content';
const posts = await getCollection('blog');
const sorted = posts.sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);
まとめ
Content Collectionsを使うことで、frontmatterのスキーマ違反をビルド時に検知できます。記事が増えてきても安心して管理できるので、ブログには必須の機能だと感じました。