📚 Content Collections

Astro 5 的 Content Layer API 提供类型安全的内容管理:

定义集合

typescript (src/content/config.ts)
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
  schema: z.object({
    title: z.string(),
    description: z.string(),
    date: z.date(),
    tags: z.array(z.string()),
    draft: z.boolean().default(false),
  }),
});

export const collections = { blog };

查询内容

astro
---
import { getCollection, getEntry } from 'astro:content';

// 获取所有文章
const posts = await getCollection('blog');

// 过滤
const published = posts.filter(p => !p.data.draft);

// 获取单篇
const post = await getEntry('blog', 'hello-world');
---

渲染 Markdown

astro
---
const { Content } = await post.render();
---

<article>
  <h1>{post.data.title}</h1>
  <Content />
</article>

📝 Markdown 支持

markdown (src/content/blog/hello.md)
---
title: Hello World
date: 2024-01-15
tags:
  - astro
  - tutorial
---

# Hello World

这是我的第一篇文章!

📄 MDX 支持

MDX 允许在 Markdown 中使用组件:

mdx
---
title: MDX 文章
---

import Counter from '../components/Counter.jsx';

# MDX 文章

这是一个 Markdown 内容。

<Counter client:visible />

可以混用 JSX 组件!

🔌 外部数据源

Content Layer API 支持从任何来源加载数据:

typescript
// 从 API 加载
const posts = defineCollection({
  loader: async () => {
    const response = await fetch('https://api.example.com/posts');
    return response.json();
  },
});