使用時機
- 登陸頁面與行銷網站
- 企業官網
- 內容豐富的網站(部落格、文件)
- 任何 SEO 與效能至關重要的專案
- 大部分為靜態且互動性極低的網站
- 需要快速初始載入與良好 Core Web Vitals 的網站
不適用於完整的網頁應用程式——請使用 vue-frontend 處理互動式應用(儀表板、CRUD 應用、即時應用)。
關鍵規則
- 預設零 JS — Astro 不會載入任何 JavaScript,除非你添加 client directive
- 永遠使用 TypeScript — 與所有 Vera Sesiom 專案相同,嚴格模式
- 對結構化內容使用 Content Collections — 部落格文章、文件、案例研究
- Islands 架構 — 僅在需要互動的地方使用 Vue/React 元件
- 預設靜態輸出 (SSG) — 僅在有動態內容需求時才使用 SSR
- 使用 Tailwind CSS 進行樣式設計 — 與 Vue 前端相同
- 吶喊式架構 — 資料夾應吶喊其業務領域,而非技術框架
決策標準:Astro vs Vue
| 何時使用 Astro | 何時使用 Vue |
|---|---|
| 登陸頁面、行銷網站 | 網頁應用(儀表板、管理後台) |
| 內容豐富(部落格、文件) | 高度互動的 UI |
| SEO 至關重要 | 需要即時功能 |
| 大部分為靜態內容 | 複雜的狀態管理 |
| 最少的互動(表單、輪播) | 完整的 SPA 導航 |
| 零 JS 是一項特色 | Vue 生態系效益至關重要 |
規則:如果網站是供人閱讀的內容 → 使用 Astro。如果是供人使用的應用程式 → 使用 Vue。
專案結構(吶喊式架構)
apps/landing/ (或 apps/website/)
├── src/
│ ├── pages/ # 基於檔案的路由 (.astro 檔案)
│ │ ├── index.astro # 首頁
│ │ ├── about.astro # 關於頁面
│ │ ├── pricing.astro # 定價頁面
│ │ ├── blog/
│ │ │ ├── index.astro # 部落格列表
│ │ │ └── [slug].astro # 部落格文章(動態)
│ │ └── contact.astro
│ ├── layouts/ # 頁面佈局
│ │ ├── BaseLayout.astro # 基礎 HTML 結構
│ │ ├── BlogLayout.astro # 部落格文章佈局
│ │ └── LandingLayout.astro # 登陸頁面佈局
│ ├── components/ # Astro 元件(預設為靜態)
│ │ ├── sections/ # 頁面區塊
│ │ │ ├── Hero.astro
│ │ │ ├── Features.astro
│ │ │ ├── Pricing.astro
│ │ │ ├── Testimonials.astro
│ │ │ └── CTA.astro
│ │ ├── ui/ # 可重複使用的 UI 原子元件
│ │ │ ├── Button.astro
│ │ │ ├── Card.astro
│ │ │ ├── Badge.astro
│ │ │ └── Input.astro
│ │ └── interactive/ # Vue/React islands
│ │ ├── ContactForm.vue # 含驗證的表單
│ │ ├── Carousel.vue # 圖片輪播
│ │ └── MobileMenu.vue # 行動導航
│ ├── content/ # 內容集合
│ │ ├── blog/ # Markdown/MDX 部落格文章
│ │ │ ├── post-1.md
│ │ │ └── post-2.mdx
│ │ └── config.ts # 集合 schema (Zod)
│ ├── styles/ # 全域樣式
│ │ └── global.css # Tailwind 匯入
│ ├── assets/ # 優化後的圖片、字型
│ │ ├── images/
│ │ └── fonts/
│ └── utils/ # 輔助函式
│ ├── date-format.ts
│ └── seo.ts
├── public/ # 靜態資源(不經處理)
│ ├── favicon.ico
│ ├── robots.txt
│ └── fonts/
├── astro.config.mjs # Astro 配置
├── tailwind.config.mjs # Tailwind 配置
├── tsconfig.json
└── package.json
Astro 元件模式
每個 .astro 檔案包含兩個部分:frontmatter(伺服器端)和模板 (HTML)。
---
// src/components/ui/Button.astro
// Frontmatter:在伺服器端執行,不產生瀏覽器 JS
export interface Props {
variant?: 'primary' | 'secondary' | 'outline'
size?: 'sm' | 'md' | 'lg'
href?: string
}
const {
variant = 'primary',
size = 'md',
href,
...rest
} = Astro.props
const baseClasses = 'inline-flex items-center justify-center font-medium rounded-lg transition-colors'
const variantClasses = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
outline: 'border-2 border-blue-600 text-blue-600 hover:bg-blue-50'
}
const sizeClasses = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2 text-base',
lg: 'px-6 py-3 text-lg'
}
const classes = `${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]}`
---
{href ? (
<a href={href} class={classes} {...rest}>
<slot />
</a>
) : (
<button class={classes} {...rest}>
<slot />
</button>
)}
重點:
- Frontmatter 在建置時(或 SSR 的請求時)執行
- 不需要
export default——模板本身就是匯出 - 使用
<slot />放置子內容 - Props 使用 TypeScript 介面進行型別定義
佈局模式
---
// src/layouts/BaseLayout.astro
import Nav from '../components/Nav.astro'
import Footer from '../components/Footer.astro'
export interface Props {
title: string
description?: string
image?: string
}
const { title, description = '', image = '/og-default.png' } = Astro.props
const canonicalURL = new URL(Astro.url.pathname, Astro.site)
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="canonical" href={canonicalURL} />
<title>{title}</title>
<meta name="description" content={description} />
<!-- OpenGraph -->
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={image} />
<meta property="og:url" href={canonicalURL} />
<meta property="og:type" content="website" />
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image" />
<slot name="head" />
</head>
<body class="bg-white text-gray-900 antialiased">
<Nav />
<main>
<slot />
</main>
<Footer />
</body>
</html>
用法:
---
// src/pages/index.astro
import BaseLayout from '../layouts/BaseLayout.astro'
import Hero from '../components/sections/Hero.astro'
---
<BaseLayout title="Vera Sesiom - Software Development" description="We build software that matters.">
<Hero />
</BaseLayout>
內容集合模式
使用 Zod schema 驗證定義結構化內容。
// src/content/config.ts
import { defineCollection, z } from 'astro:content'
const blogCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
author: z.string().default('Vera Sesiom'),
image: z.object({
url: z.string(),
alt: z.string()
}).optional(),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false)
})
})
export const collections = {
blog: blogCollection
}
---
title: "我們為何選擇 Astro 建置登陸頁面"
description: "效能與開發者體驗至關重要。以下是 Astro 成為我們內容網站首選的原因。"
pubDate: 2024-01-15
author: "技術主管"
image:
url: "/images/blog/astro-landing.jpg"
alt: "現代網站上的 Astro 標誌"
tags: ["astro", "效能", "架構"]
---
內容放在這裡...
---
// src/pages/blog/index.astro
import { getCollection } from 'astro:content'
import BaseLayout from '../../layouts/BaseLayout.astro'
const posts = (await getCollection('blog'))
.filter(post => !post.data.draft)
.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf())
---
<BaseLayout title="部落格" description="來自 Vera Sesiom 的最新文章">
<h1>部落格</h1>
<ul>
{posts.map(post => (
<li>
<a href={`/blog/${post.slug}`}>
<h2>{post.data.title}</h2>
<p>{post.data.description}</p>
<time>{post.data.pubDate.toLocaleDateString()}</time>
</a>
</li>
))}
</ul>
</BaseLayout>
---
// src/pages/blog/[slug].astro
import { getCollection } from 'astro:content'
import BaseLayout from '../../layouts/BaseLayout.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()
---
<BaseLayout title={post.data.title} description={post.data.description}>
<article>
<header>
<h1>{post.data.title}</h1>
<time>{post.data.pubDate.toLocaleDateString()}</time>
<p>作者:{post.data.author}</p>
</header>
<Content />
</article>
</BaseLayout>
Islands 架構(Vue 元件)
互動式元件僅在需要時才載入 JS。使用 client directives 控制水合。
<!-- src/components/interactive/ContactForm.vue -->
<script setup lang="ts">
import { ref, computed } from 'vue'
const form = ref({
name: '',
email: '',
message: ''
})
const errors = ref<Record<string, string>>({})
const isValid = computed(() => {
return form.value.name &&
form.value.email.includes('@') &&
form.value.message.length > 10
})
async function submitForm() {
if (!isValid.value) return
// Submit to API
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form.value)
})
if (response.ok) {
// Handle success
form.value = { name: '', email: '', message: '' }
}
}
</script>
<template>
<form @submit.prevent="submitForm" class="space-y-4">
<div>
<label for="name">姓名</label>
<input v-model="form.name" type="text" id="name" required />
</div>
<div>
<label for="email">Email</label>
<input v-model="form.email" type="email" id="email" required />
</div>
<div>
<label for="message">訊息</label>
<textarea v-model="form.message" id="message" rows="4" required />
</div>
<button type="submit" :disabled="!isValid">
發送訊息
</button>
</form>
</template>
在 Astro 中使用:
---
// src/pages/contact.astro
import BaseLayout from '../layouts/BaseLayout.astro'
import ContactForm from '../components/interactive/ContactForm.vue'
---
<BaseLayout title="聯絡我們">
<h1>與我們聯繫</h1>
<p>我們很樂意聽取您的意見。</p>
<!-- client:visible = 當捲動到可視區域時進行水合(最佳實踐) -->
<ContactForm client:visible />
</BaseLayout>
Client Directives 決策樹
| Directive | 使用時機 | JS 載入時機 |
|---|---|---|
| 無 directive | 靜態內容,無互動 | 零 JS |
client:visible | 折疊線以下的互動(表單、輪播)— 預設 | 當捲動到可視區域時 |
client:load | 折疊線以上關鍵互動 | 立即 |
client:idle | 非關鍵增強功能(分析、聊天) | 頁面閒置後 |
client:media | 根據斷點條件使用(行動導航) | 當媒體查詢符合時 |
client:only | SPA 類元件(跳過 SSR) | 立即,不進行 SSR |
最佳實踐:
- 預設不使用 directive——純靜態
- 需要互動時,預設使用
client:visible - 謹慎使用
client:load——僅用於折疊線以上關鍵區域 - 使用
client:idle處理非阻塞增強功能
---
<!-- 良好範例 -->
import Hero from './Hero.astro' <!-- 靜態,無 JS -->
import Carousel from './Carousel.vue'
import MobileMenu from './MobileMenu.vue'
import Chat from './Chat.vue'
import Stats from './Stats.astro' <!-- 靜態計數器 = CSS -->
<Hero /> <!-- 靜態,無需水合 -->
<Carousel client:visible /> <!-- 可見時水合 -->
<MobileMenu client:media="(max-width: 768px)" /> <!-- 僅在行動裝置 -->
<Chat client:idle /> <!-- 頁面穩定後 -->
<Stats /> <!-- 純 CSS 動畫,無需 JS -->
圖片優化
使用 astro:assets 進行自動優化。
---
// src/pages/index.astro
import { Image } from 'astro:assets'
import heroImage from '../assets/images/hero.png'
---
<Image
src={heroImage}
alt="英雄圖片"
width={800}
height={600}
loading="lazy"
format="webp"
/>
對於來自 CMS 或外部來源的圖片:
---
import { Image } from 'astro:assets'
---
<Image
src="https://example.com/image.jpg"
alt="外部圖片"
width={800}
height={600}
/>
規則:
- 務必指定
width和height以防止 CLS - 對折疊線以下的圖片使用
loading="lazy" - 偏好使用
webp或avif格式 - 保持英雄圖片優化並採用適當尺寸
SEO 模式
---
// src/components/SEO.astro
export interface Props {
title: string
description: string
image?: string
article?: boolean
publishedTime?: Date
author?: string
tags?: string[]
}
const {
title,
description,
image = '/og-default.png',
article = false,
publishedTime,
author,
tags = []
} = Astro.props
const canonicalURL = new URL(Astro.url.pathname, Astro.site)
const imageURL = new URL(image, Astro.site)
---
<!-- 主要 Meta 標籤 -->
<title>{title}</title>
<meta name="title" content={title} />
<meta name="description" content={description} />
<link rel="canonical" href={canonicalURL} />
<!-- Open Graph -->
<meta property="og:type" content={article ? 'article' : 'website'} />
<meta property="og:url" content={canonicalURL} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={imageURL} />
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={imageURL} />
<!-- 文章專用 -->
{article && publishedTime && (
<meta property="article:published_time" content={publishedTime.toISOString()} />
)}
{article && author && (
<meta property="article:author" content={author} />
)}
{article && tags.map(tag => (
<meta property="article:tag" content={tag} />
))}
<!-- JSON-LD 結構化資料 -->
<script type="application/ld+json" set:html={JSON.stringify({
'@context': 'https://schema.org',
'@type': article ? 'Article' : 'WebPage',
headline: title,
description,
image: imageURL,
url: canonicalURL,
...(article && publishedTime && { datePublished: publishedTime.toISOString() }),
...(article && author && { author: { '@type': 'Person', name: author } })
})} />