技術 · 2 min read

Astro 入門指南:打造高效能靜態網站

什麼是 Astro?

Astro 是一個現代的靜態網站生成器,專為內容驅動的網站設計。它的核心理念是「送出更少的 JavaScript」。

核心特色

Islands Architecture

Astro 採用 Islands Architecture(島嶼架構),只在需要互動的元件上載入 JavaScript:

---
// 靜態元件 - 零 JS
import Header from '../components/Header.astro';
// 互動元件 - 按需載入 JS
import Counter from '../components/Counter.tsx';
---

<Header />
<Counter client:visible />

Content Collections

Content Collections 提供型別安全的內容管理:

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

const blog = defineCollection({
  schema: z.object({
    title: z.string(),
    pubDate: z.coerce.date(),
    tags: z.array(z.string()),
  }),
});

export const collections = { blog };

查詢內容

使用 getCollection 查詢所有文章:

import { getCollection } from 'astro:content';

const posts = await getCollection('blog');
const sortedPosts = posts.sort(
  (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);

效能比較

框架首次載入 JSBuild 速度
Astro~0 KB
Next.js~80 KB
Gatsby~70 KB

結論

如果你的網站以內容為主(部落格、文件、行銷頁面),Astro 是一個絕佳的選擇。它的零 JS 預設策略能帶來極佳的效能體驗。

提示: 使用 pnpm create astro@latest 就能快速開始。