Astro 網頁框架
選擇性閱讀規則
從以下文件開始:
references/senior-master-standard.mdreferences/usage-routing.mdreferences/quality-checklist.md
然後僅載入與使用者實際任務相符的繼承文件、腳本、資產或範例。
概覽
Astro 是專為內容豐富的網站(部落格、文件、作品集、行銷網站與電子商務)設計的網頁框架。其核心創新在於島嶼架構:預設情況下,Astro 不會向瀏覽器傳送任何 JavaScript。互動式元件會以獨立的「島嶼」形式選擇性地水合(hydrate)。Astro 支援同時在同一個專案中使用 React、Vue、Svelte、Solid 及其他 UI 框架,讓您能為每個元件選擇最合適的工具。
何時使用此技能
- 當您正在建立部落格、文件網站、行銷頁面或作品集時
- 當效能與核心網頁指標(Core Web Vitals)為最高優先事項時
- 當專案為內容密集,包含大量 Markdown 或 MDX 檔案時
- 當您想要靜態輸出(SSG),並可選擇為動態路由啟用 SSR 時
- 當使用者詢問關於
.astro檔案、Astro.props、內容集合或client:指令時
運作方式
步驟 1:專案設定
npm create astro@latest my-site
cd my-site
npm install
npm run dev
依需求新增整合:
npx astro add tailwind # Tailwind CSS
npx astro add react # React 元件支援
npx astro add mdx # MDX 支援
npx astro add sitemap # 自動產生 sitemap.xml
npx astro add vercel # Vercel SSR 適配器
專案結構:
src/
pages/ ← 基於檔案的路由(.astro, .md, .mdx)
layouts/ ← 可重複使用的頁面框架
components/ ← UI 元件(.astro, .tsx, .vue 等)
content/ ← 型別安全的內容集合(Markdown/MDX)
styles/ ← 全域 CSS
public/ ← 靜態資產(原封不動複製)
astro.config.mjs ← 框架設定檔
步驟 2:Astro 元件語法
.astro 檔案在頂端有一個程式碼柵欄(僅限伺服器端),下方是樣板:
---
// src/components/Card.astro
// 此區塊僅在伺服器端執行 — 絕不會在瀏覽器中執行
interface Props {
title: string;
href: string;
description: string;
}
const { title, href, description } = Astro.props;
---
<article class="card">
<h2><a href={href}>{title}</a></h2>
<p>{description}</p>
</article>
<style>
/* 自動作用於此元件 */
.card { border: 1px solid #eee; padding: 1rem; }
</style>
步驟 3:基於檔案的頁面與路由
src/pages/index.astro → /
src/pages/about.astro → /about
src/pages/blog/[slug].astro → /blog/:slug (動態路由)
src/pages/blog/[...path].astro → /blog/* (萬用路由)
使用 getStaticPaths 的動態路由:
---
// 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();
---
<h1>{post.data.title}</h1>
<Content />
步驟 4:內容集合
內容集合提供對 Markdown 和 MDX 檔案的型別安全存取:
// src/content/config.ts
import { z, defineCollection } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
date: z.coerce.date(),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false),
}),
});
export const collections = { blog };
---
// src/pages/blog/index.astro
import { getCollection } from 'astro:content';
const posts = (await getCollection('blog'))
.filter(p => !p.data.draft)
.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
---
<ul>
{posts.map(post => (
<li>
<a href={`/blog/${post.slug}`}>{post.data.title}</a>
<time>{post.data.date.toLocaleDateString()}</time>
</li>
))}
</ul>
步驟 5:島嶼 — 選擇性水合
預設情況下,UI 框架元件會渲染為靜態 HTML,不含任何 JavaScript。使用 client: 指令來進行水合:
---
import Counter from '../components/Counter.tsx'; // React 元件
import VideoPlayer from '../components/VideoPlayer.svelte';
---
<!-- 靜態 HTML — 不向瀏覽器傳送 JavaScript -->
<Counter initialCount={0} />
<!-- 頁面載入時立即水合 -->
<Counter initialCount={0} client:load />
<!-- 當元件滾動到可視區域時水合 -->
<VideoPlayer src="/demo.mp4" client:visible />
<!-- 僅在瀏覽器閒置時水合 -->
<Analytics client:idle />
<!-- 僅在特定媒體查詢條件下才水合 -->
<MobileMenu client:media="(max-width: 768px)" />
步驟 6:版面配置
---
// src/layouts/BaseLayout.astro
interface Props {
title: string;
description?: string;
}
const { title, description = 'My Astro Site' } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<title>{title}</title>
<meta name="description" content={description} />
</head>
<body>
<nav>...</nav>
<main>
<slot /> <!-- 頁面內容在此處渲染 -->
</main>
<footer>...</footer>
</body>
</html>
---
// src/pages/about.astro
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="About Us">
<h1>關於我們</h1>
<p>歡迎來到我們的公司...</p>
</BaseLayout>
步驟 7:SSR 模式(按需渲染)
透過設定適配器來啟用 SSR,以支援動態頁面:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';
export default defineConfig({
output: 'hybrid', // 'static' | 'server' | 'hybrid'
adapter: vercel(),
});
使用 export const prerender = false 選擇性地將個別頁面納入 SSR。
範例
範例 1:含 RSS 資訊提供的部落格
// src/pages/rss.xml.ts
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
export async function GET(context) {
const posts = await getCollection('blog');
return rss({
title: '我的部落格',
description: '最新文章',
site: context.site,
items: posts.map(post => ({
title: post.data.title,
pubDate: post.data.date,
link: `/blog/${post.slug}/`,
})),
});
}
範例 2:API 端點(SSR)
// src/pages/api/subscribe.ts
import type { APIRoute } from 'astro';
export const POST: APIRoute = async ({ request }) => {
const { email } = await request.json();
if (!email) {
return new Response(JSON.stringify({ error: '需要提供電子郵件' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
});
}
await addToNewsletter(email);
return new Response(JSON.stringify({ success: true }), { status: 200 });
};
範例 3:React 元件作為島嶼
// src/components/SearchBox.tsx
import { useState } from 'react';
export default function SearchBox() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
async function search(e: React.FormEvent) {
e.preventDefault();
const data = await fetch(`/api/search?q=${query}`).then(r => r.json());
setResults(data);
}
return (
<form onSubmit={search}>
<input value={query} onChange={e => setQuery(e.target.value)} />
<button type="submit">搜尋</button>
<ul>{results.map(r => <li key={r.id}>{r.title}</li>)}</ul>
</form>
);
}
---
import SearchBox from '../components/SearchBox.tsx';
---
<!-- 立即水合 — 此島嶼為互動式 -->
<SearchBox client:load />
最佳實踐
- ✅ 將大部分元件保留為靜態的
.astro檔案 — 僅對必須互動的元件進行水合 - ✅ 對所有 Markdown/MDX 內容使用內容集合 — 可獲得型別安全性與自動驗證
- ✅ 對摺疊以下的元件,優先使用
client:visible而非client:load,以減少初始 JavaScript - ✅ 使用
import.meta.env來管理環境變數 — 將公開變數加上PUBLIC_前綴 - ✅ 從
astro:transitions新增<ViewTransitions />,以實現流暢的頁面導航,無需完整的 SPA - ❌ 不要對每個元件都使用
client:load— 這會削弱 Astro 的效能優勢 - ❌ 不要在會用於客戶端樣板的
.astro前端區塊(frontmatter)中放入機密資訊 - ❌ 在靜態模式下,不要略過動態路由的
getStaticPaths— 建置將會失敗
安全性與安全注意事項
.astro檔案中的前端區塊(frontmatter)程式碼僅在伺服器端執行,絕不會暴露給瀏覽器。- 僅對非敏感值使用
import.meta.env.PUBLIC_*。私有環境變數(沒有PUBLIC_前綴)絕不會傳送給客戶端。 - 使用 SSR 模式時,在進行資料庫查詢或 API 呼叫之前,務必驗證所有
Astro.request輸入。 - 在透過
set:html渲染前,務必清理任何使用者提供的內容 — 它會繞過自動跳脫(auto-escaping)。
常見陷阱
-
問題: React/Vue 元件的 JavaScript 未在瀏覽器中執行 解決方案: 新增
client:指令(client:load,client:visible等)— 若無此指令,元件僅會渲染為靜態 HTML。 -
問題: 開發期間內容更新後,
getStaticPaths的資料過時了 解決方案: Astro 的開發伺服器會監看內容檔案 — 如果對content/config.ts的變更未反映出來,請重新啟動伺服器。 -
問題:
Astro.props的型別為any— 無自動補全 解決方案: 在前端區塊(frontmatter)中定義Props介面或型別,Astro 會自動推斷。 -
問題: 來自
.astro元件的 CSS 外洩到其他元件 解決方案:.astro的<style>標籤中的樣式會自動作用域化。僅在明確想要鎖定子元件時才使用:global()。
相關技能
@sveltekit— 當您需要一個具有反應式 UI 的全端框架(相對於 Astro 的內容導向)@nextjs-app-router-patterns— 當您需要一個以 React 為優先的全端框架@tailwind-patterns— 使用 Tailwind CSS 為 Astro 網站設定樣式@progressive-web-app— 為 Astro 網站新增 PWA 功能
限制
- 僅在任務與上述範圍明確相符時使用此技能。
- 請勿將輸出視為環境特定驗證、測試或專家審查的替代方案。
- 如果缺少所需的輸入、權限、安全邊界或成功標準,請停止並要求釐清。