技术
Astro前端

用 Astro Content Collections 搭建双栏博客

在给自己的个人站添加人文和技术两个内容板块时, 需要一套能同时管理两种文章的内容系统。 Astro 的 Content Collections 正好解决这个问题。

为什么选 Content Collections

不用 Content Collections 的话,文章散落在 src/pages/posts/ 里, 要自己写 loader 来解析 frontmatter、排序、筛选。而 Content Collections:

双栏架构

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

const humanities = defineCollection({
  type: 'content',
  schema: z.object({
    title: z.string(),
    date: z.string(),
    tags: z.array(z.string()).optional(),
  }),
});

const tech = defineCollection({
  type: 'content',
  schema: z.object({
    title: z.string(),
    date: z.string(),
    tags: z.array(z.string()).optional(),
  }),
});

export const collections = { humanities, tech };

文件结构:

src/content/
├── humanities/   # 人文类文章
│   └── why-digital-life-fears-loneliness.md
└── tech/         # 技术分享
    └── astro-content-collections.md

查询文章

import { getCollection } from 'astro:content';

const posts = await getCollection('tech');
// 按日期排序
const sorted = posts.sort((a, b) =>
  new Date(b.data.date).getTime() - new Date(a.data.date).getTime()
);

参考