入门教程 - 群岛架构与内容驱动

知识库
知识库文档
/tech-stacks/astro/tutorial/入门教程 - 群岛架构与内容驱动.md

文档

Astro 入门教程:群岛架构与内容驱动

一、Astro 是什么?

Astro 是专注于内容驱动网站的现代静态站点生成器。它的核心理念是"Islands Architecture(群岛架构)"——页面默认是纯静态 HTML(零 JavaScript),仅在需要交互的地方引入"岛屿"(React/Vue/Svelte 组件水合到页面中)。

为什么这很重要?

传统 SPA 框架下,一个博客首页可能加载 200KB+ 的 JavaScript,而 Astro 的同一页面可能仅 0KB。对于文档站、营销站、电商产品页等以内容为主的场景,这是巨大的性能优势。

二、Islands Architecture 详解

┌─────────────────────────────────────┐
│           纯 HTML 海洋               │
│  (导航栏、标题、正文、页脚)            │
│                                     │
│  ┌─────────┐  ┌──────────────┐      │
│  │ React   │  │   Svelte      │      │
│  │ 轮播图   │  │  实时搜索      │      │
│  └─────────┘  └──────────────┘      │
│     ↑ 水合岛屿      ↑ 另一个岛屿      │
└─────────────────────────────────────┘

client 指令控制水合时机

指令 水合时机 适用场景
client:load 页面加载后立即 关键交互(导航菜单)
client:idle 浏览器空闲时 低优先级组件
client:visible 进入视口时 懒加载组件(评论区)
client:media 匹配媒体查询时 响应式组件
client:only 仅客户端渲染 依赖浏览器 API 的组件

三、内容集合(Content Collections)

Astro 2.0+ 的核心特性,为 Markdown/MDX 提供类型安全:

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

const blogCollection = defineCollection({
  type: "content",
  schema: z.object({
    title: z.string(),
    date: z.date(),
    description: z.string().optional(),
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
  }),
});

export const collections = { blog: blogCollection };

使用:

---
import { getCollection } from "astro:content";

const posts = await getCollection("blog", ({ data }) => !data.draft);
const sortedPosts = posts.sort(
  (a, b) => b.data.date.getTime() - a.data.date.getTime()
);
---

<ul>
  {sortedPosts.map((post) => (
    <li>
      <a href={`/blog/${post.slug}`}>{post.data.title}</a>
      <time>{post.data.date.toLocaleDateString()}</time>
    </li>
  ))}
</ul>

四、路由系统

src/pages/
├── index.astro          → /
├── about.astro          → /about
├── blog/
│   ├── index.astro      → /blog
│   └── [slug].astro     → /blog/:slug(动态路由)
├── rss.xml.js           → /rss.xml(API 端点)
└── 404.astro            → 自定义 404

动态路由 + SSG

---
// src/pages/blog/[slug].astro
export async function getStaticPaths() {
  const posts = await getCollection("blog");
  return posts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
  }));
}

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

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

五、视图过渡(View Transitions)

Astro 3.0+ 内置 SPA 般的页面过渡:

---
import { ViewTransitions } from "astro:transitions";
---

<html>
  <head>
    <ViewTransitions />
    <!-- 页面切换时自动应用原生 View Transition API -->
  </head>
  <body>
    <slot />
  </body>
</html>

六、部署

npm run build  # 输出到 dist/

# 支持所有主流平台:
# - Vercel:自动检测 Astro 框架
# - Netlify:用 @astrojs/netlify 适配器(SSR 模式)
# - Cloudflare Pages:用 @astrojs/cloudflare 适配器
# - 静态托管(GitHub Pages/S3 等):默认静态模式

七、思考题

  1. "零 JS" 真的意味着完全不能用 JavaScript 吗?什么情况需要 JS?
  2. Islands Architecture 和 Micro Frontends 有何异同?
  3. 如果一个页面有 20 个交互组件,Islands Architecture 还会有性能优势吗?

信息

路径
/tech-stacks/astro/tutorial/入门教程 - 群岛架构与内容驱动.md
更新时间
2026/5/31