跳到主内容

如何用 Astro 构建一个静态博客

从零梳理 Astro 内容集合、静态生成与边缘部署的关键点。

Astro 的内容集合(Content Collections)让 Markdown 文章拥有类型安全的 frontmatter。

内容集合

使用 glob loader 自动扫描 src/content/posts

import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';

const posts = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/posts' }),
  schema: z.object({
    title: z.string(),
    date: z.coerce.date(),
    draft: z.boolean().default(false),
  }),
});

静态生成

getStaticPaths 会为每篇文章生成独立页面,构建产物全部是 HTML,可部署到任意静态托管。

部署

构建命令:

npm install
npm run build   # astro build && pagefind --site dist

输出目录 dist 直接上传到边缘静态托管即可。

© 2026 站长 · 本文采用署名-非商业性使用 4.0 国际许可协议