Astro 5移行ガイド:Content Layer APIの活用法
Astro 4からAstro 5への移行手順と、新しいContent Layer APIを活用したコンテンツ管理の実践方法を解説します。
AstroSSGContent Layer
Astro 5の注目ポイント
Astro 5は、コンテンツ駆動サイトの構築において大きな進化を遂げました。最大の変更点はContent Layer APIの刷新で、より柔軟なデータソースの統合が可能になっています。
当社の自社サイトもAstro 5で構築しており、その移行経験をもとに実践的なガイドをまとめました。
Content Layer APIの変更点
Astro 5では、Content Collectionsの定義方法が変わりました。新しいloaderベースのアーキテクチャにより、ローカルファイルだけでなく外部APIやCMSからのデータ取得も統一的に扱えます。
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(),
}),
});
globローダーを使用することで、ファイルシステムベースのコンテンツ管理が簡潔に記述できます。
移行時の注意点
移行で最も注意すべきは、getEntry()やgetCollection()のAPI変更です。Astro 5ではrender()関数がastro:contentからインポートされるようになり、エントリのレンダリング方法が変わっています。
---
import { getCollection, render } from 'astro:content';
const posts = await getCollection('blog');
const { Content, headings } = await render(posts[0]);
---
また、slugプロパティがidに変更されている点も見落としがちなポイントです。既存のルーティングロジックを確認し、適切に修正しましょう。
パフォーマンスの改善
Astro 5ではビルドパフォーマンスも大幅に向上しています。当社サイトでは、100ページ規模のビルドが約30%高速化しました。特にContent Collectionsのキャッシュ機構が改善され、差分ビルドが効率的に動作します。
移行コストは比較的低く、メリットは大きいため、Astro 4ユーザーには早期の移行をお勧めします。