コンテンツコレクションを追加してブログ投稿を管理して、チュートリアルを拡張しましょう。
Fri Aug 02
Written by: Astro学習者
Content collections are a powerful way to manage groups of similar content, such as blog posts. Collections help to organize your documents, validate your YAML frontmatter, and provide automatic TypeScript type-safety for all of your content (even if you don’t write any TypeScript yourself).
コンテンツコレクションは、ブログ記事などの似たようなコンテンツのグループを管理するための強力な方法です。 コレクションはドキュメントを整理し、YAMLフロントマターを検証し、すべてのコンテンツに対して自動的にTypeScriptの型安全性を提供するのに役立ちます(たとえあなた自身がTypeScriptを書かなくても)。
Move your folder of blog posts into src/content/
Create a schema to define your blog post frontmatter
Use getCollection() to get blog post content and metadata
ブログ記事のフォルダを src/content/ に移動する
スキーマを作成してブログ記事のフロントマターを定義する
getCollection() を使用してブログ記事のコンテンツとメタデータを取得する
You will need an existing Astro project with Markdown or MDX files in the src/pages/ folder.
This tutorial uses the Build a Blog tutorial’s finished project to demonstrate converting a blog to content collections. You can fork and use that codebase locally, or complete the tutorial in the browser by editing the blog tutorial’s code in StackBlitz.
You can instead follow these steps with your own Astro project, but you will need to adjust the instructions for your codebase.
We recommend using our sample project to complete this short tutorial first. Then, you can use what you have learned to create content collections in your own project.
src/pages/フォルダにMarkdownまたはMDXファイルがある、既存のAstroプロジェクトが必要です。
このチュートリアルでは、Build a Blog チュートリアルの完成したプロジェクトを使用して、ブログをコンテンツコレクションに変換するデモンストレーションを行います。そのコードベースをローカルにフォークして使用することもできますし、StackBlitz でブログチュートリアルのコードを編集してブラウザ上でチュートリアルを完成させることもできます。
代わりに、自分のAstroプロジェクトでこの手順を実行することもできるが、その場合は自分のコードベースに合わせて手順を調整する必要がある。
この短いチュートリアルを完了するために、まず私たちのサンプルプロジェクトを使用することをお勧めします。その後、学んだことを自分のプロジェクトでコンテンツコレクションを作成するために使用することができます。
In the Build a Blog introductory tutorial, you learned about Astro’s built-in file-based routing: any .astro, .md, or .mdx file anywhere within the src/pages/ folder automatically became a page on your site.
To create your first blog post at https://example.com/posts/post-1/, you created a /posts/ folder and added the file post-1.md. You then added a new Markdown file to this folder every time you wanted to add a new blog post to your site.
ブログの構築入門チュートリアルでは、Astroの組み込みファイルベースのルーティングについて学びました:src/pages/フォルダ内の任意の場所にある.astro、.md、または.mdxファイルは、自動的にあなたのサイトのページになります。
https://example.com/posts/post-1/、最初のブログ記事を作成するために、/posts/フォルダを作成し、post-1.mdファイルを追加しました。そして、サイトに新しいブログ記事を追加するたびに、このフォルダに新しいMarkdownファイルを追加しました。
Even when using content collections, you will still use the src/pages/ folder for individual pages, such as your About Me page. But, moving your blog posts to the special src/content/ folder will allow you to use more powerful and performant APIs to generate your blog post index and display your individual blog posts.
At the same time, you’ll receive better guidance and autocompletion in your code editor because you will have a schema to define a common structure for each post that Astro will help you enforce. In your schema, you can specify when frontmatter properties are required, such as a description or an author, and which data type each property must be, such as a string or an array. This leads to catching many mistakes sooner, with descriptive error messages telling you exactly what the problem is.
Read more about Astro’s content collections in our guide, or get started with the instructions below to convert a basic blog from src/pages/posts/ to src/content/posts/.
コンテンツ・コレクションを使用する場合でも、About Meページのような個々のページにはsrc/pages/フォルダを使用します。しかし、ブログ記事を特別なsrc/content/フォルダに移動することで、ブログ記事のインデックスを生成し、個々のブログ記事を表示するために、より強力でパフォーマンスの高いAPIを使用できるようになります。
同時に、各投稿に共通の構造を定義するスキーマを用意し、Astroがそれを実施する手助けをするため、コードエディターでより良いガイダンスとオートコンプリートを受けることができます。スキーマでは、説明文や作者などのフロントマター・プロパティが必要な場合や、文字列や配列など、各プロパティがどのデータ型でなければならないかを指定できます。これは、説明的なエラーメッセージで問題の内容を正確に伝えることで、多くのミスをより早く発見することにつながります。
Astroのコンテンツ・コレクションについては、ガイドをご覧ください。また、基本的なブログをsrc/pages/posts/からsrc/content/posts/に変換するには、以下の手順で始めてください。
The steps below show you how to extend the final product of the Build a Blog tutorial by creating a content collection for the blog posts.
以下のステップでは、ブログ記事用のコンテンツコレクションを作成することで、チュートリアルのBuild a Blogの最終成果物を拡張する方法を示します。
Upgrade to the latest version of Astro, and upgrade all integrations to their latest versions by running the following commands in your terminal:
# Upgrade to Astro v4.x
npm install astro@latest
# Example: upgrade the blog tutorial Preact integration
npm install @astrojs/preact@latest
Tip
If you are using your own project, then be sure to update any dependencies you have installed. The example blog tutorial codebase only uses the Preact integration.
The blog tutorial uses the base (least strict) TypeScript setting. In order to use content collections, you must set up TypeScript for content collections either by using the strict or strictest setting, or by adding two options in tsconfig.json.
In order to use content collections without writing TypeScript in the rest of the blog tutorial example, add the following two TypeScript configuration options to the config file:
{
// Note: No change needed if you use "astro/tsconfigs/strict" or "astro/tsconfigs/strictest"
"extends": "astro/tsconfigs/base",
"compilerOptions": {
"strictNullChecks": true,
"allowJs": true
}
}
ターミナルで以下のコマンドを実行して、Astroを最新バージョンにアップグレードし、すべてのインテグレーションを最新バージョンにアップグレードします:
# Upgrade to Astro v4.x
npm install astro@latest
# Example: upgrade the blog tutorial Preact integration
npm install @astrojs/preact@latest
Tip
独自のプロジェクトを使用している場合は、インストールされている依存関係を必ず更新してください。ブログチュートリアルのコードベース例では、Preactインテグレーションのみを使用しています。
ブログのチュートリアルでは、基本的な(最も厳密でない)TypeScript設定を使用している。コンテンツ・コレクションを使用するには、strictまたはstrictest設定を使用するか、tsconfig.jsonに2つのオプションを追加して、コンテンツ・コレクション用のTypeScriptを設定する必要があります。
ブログ・チュートリアルの残りの例でTypeScriptを書かずにコンテンツ・コレクションを使うには、設定ファイルに以下の2つのTypeScript設定オプションを追加する:
{
// Note: No change needed if you use "astro/tsconfigs/strict" or "astro/tsconfigs/strictest"
"extends": "astro/tsconfigs/base",
"compilerOptions": {
"strictNullChecks": true,
"allowJs": true
}
}
Create a new collection (folder) called src/content/posts/.
Move all your existing blog posts (.md files) from src/pages/posts/ into this new collection.
Create a src/content/config.ts file to define a schema for your postsCollection. For the existing blog tutorial code, add the following contents to the file to define all the frontmatter properties used in its blog posts:
// Import utilities from `astro:content`
import { z, defineCollection } from "astro:content";
// Define a `type` and `schema` for each collection
const postsCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
pubDate: z.date(),
description: z.string(),
author: z.string(),
image: z.object({
url: z.string(),
alt: z.string()
}),
tags: z.array(z.string())
})
});
// Export a single `collections` object to register your collection(s)
export const collections = {
posts: postsCollection,
};
In order for Astro to recognize your schema, quit the dev server (CTRL + C) and run the following command: npx astro sync. This will define the astro:content module for the Content Collections API. Restart the dev server to continue with the tutorial.
src/content/posts/という新しいコレクション(フォルダ)を作成する。
既存のすべてのブログ記事(.mdファイル)をsrc/pages/posts/からこの新しいコレクションに移動します。
src/content/config.tsファイルを作成し、postsCollectionのスキーマを定義します。既存のブログチュートリアルのコードについて、そのブログ記事で使用されるすべてのfrontmatterプロパティを定義するために、以下の内容をファイルに追加します:
// Import utilities from `astro:content`
import { z, defineCollection } from "astro:content";
// Define a `type` and `schema` for each collection
const postsCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
pubDate: z.date(),
description: z.string(),
author: z.string(),
image: z.object({
url: z.string(),
alt: z.string()
}),
tags: z.array(z.string())
})
});
// Export a single `collections` object to register your collection(s)
export const collections = {
posts: postsCollection,
};
Astroにスキーマを認識させるには、開発サーバーを終了し(CTRL + C)、次のコマンドを実行します: npx astro sync.これで、Content Collections API 用の astro:content モジュールが定義されます。チュートリアルを続けるには、開発サーバーを再起動します。
Create a page file called src/pages/posts/[...slug].astro. Your Markdown and MDX files no longer automatically become pages using Astro’s file-based routing when they are inside a collection, so you must create a page responsible for generating each individual blog post.
Add the following code to query your collection to make each blog post’s slug and page content available to each page it will generate:
---
import { getCollection } from 'astro:content';
import MarkdownPostLayout from '../../layouts/MarkdownPostLayout.astro';
export async function getStaticPaths() {
const blogEntries = await getCollection('posts');
return blogEntries.map(entry => ({
params: { slug: entry.slug }, props: { entry },
}));
}
const { entry } = Astro.props;
const { Content } = await entry.render();
---
Render your post <Content /> within the layout for Markdown pages. This allows you to specify a common layout for all of your posts.
---
import { getCollection } from 'astro:content';
import MarkdownPostLayout from '../../layouts/MarkdownPostLayout.astro';
export async function getStaticPaths() {
const blogEntries = await getCollection('posts');
return blogEntries.map(entry => ({
params: { slug: entry.slug }, props: { entry },
}));
}
const { entry } = Astro.props;
const { Content } = await entry.render();
---
+<MarkdownPostLayout frontmatter={entry.data}>
+<Content />
+</MarkdownPostLayout>
Remove the layout definition in each individual post’s frontmatter. Your content is now wrapped in a layout when rendered, and this property is no longer needed.
---
-layout: ../../layouts/MarkdownPostLayout.astro
title: 'My First Blog Post'
pubDate: 2022-07-01
...
---