Communitygithub.com

ASoudy/AGS

使用 Astro 建立內容導向網站 — 預設零 JavaScript、島嶼架構、多框架元件,並支援 Markdown/MDX。

AGS 是什麼?

此技能涵蓋 Astro Web 框架,一個專為內容豐富網站(如部落格、文件、作品集和行銷頁面)設計的現代化靜態網站產生器。其核心創新是「島嶼架構 (Islands Architecture)」,預設不傳送任何 JavaScript 至瀏覽器,僅對需要互動的元件選擇性地進行水合 (hydrate),從而顯著提升性能與 Core Web Vitals 指標。Astro 可在同一個專案中同時支援 React、Vue、Svelte、Solid 等多種 UI 框架,讓開發者為每個元件挑選最合適的工具。此技能詳細說明了專案初始化、.astro 元件語法、基於檔案的頁面路由、類型安全的內容集合 (Content Collections)、選擇性水合的 `client:` 指令、佈局 (Layouts)、SSR 模式設定,以及常見的最佳實踐與陷阱。它適用於 Claude Code、Cursor、Codex 等 AI 編碼代理,協助開發者快速建立高性能、內容驅動的網站。

相容平台✓Claude Code~Codex CLI✓Cursor✓Gemini CLI
npx skills add https://github.com/ASoudy/AGS/tree/HEAD/AGAS/plugins/antigravity-awesome-skills-claude/skills/astro

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Astro Web 框架

概述

Astro 是一個專為內容豐富網站設計的 Web 框架——部落格、文件、作品集、行銷網站和電子商務。其核心創新是島嶼架構:預設情況下,Astro 不向瀏覽器傳送任何 JavaScript。互動式元件會作為孤立的「島嶼」被選擇性地水合。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>About Us</h1>
  <p>Welcome to our company...</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 Feed 的部落格

// 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: 'My Blog',
    description: 'Latest posts',
    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: 'Email required' }), {
      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">Search</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 渲染前,請清除任何使用者提供的內容 — 它會繞過自動跳脫。

常見陷阱

  • 問題: 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 功能

限制

  • 僅在任務明確符合上述範圍時使用此技能。
  • 請勿將輸出視為針對特定環境驗證、測試或專家審查的替代方案。
  • 如果缺少必要的輸入、權限、安全邊界或成功標準,請停下來並請求澄清。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ASoudy/AGS

Advanced JavaScript animation library skill for creating complex, high-performance web animations.

ASoudy/AGS

Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis.

ASoudy/AGS

One sentence - what this skill does and when to invoke it

ASoudy/AGS

Audit and fix animation performance issues including layout thrashing, compositor properties, scroll-linked motion, and blur effects. Use when animations stutter, transitions jank, or reviewing CSS/JS animation performance.

ASoudy/AGS

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

ASoudy/AGS

Pull a YouTube video transcript into a queryable markdown vault with yt-dlp subtitle discovery, VTT cleanup, metadata frontmatter, and capture-seed stubs.

ASoudy/AGS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

ASoudy/AGS

Generates high-converting Next.js/React landing pages with Tailwind CSS. Uses PAS, AIDA, and BAB frameworks for optimized copy/components (Heroes, Features, Pricing). Focuses on Core Web Vitals/SEO.

ASoudy/AGS

AI-powered animation tool for creating motion in logos, UI, icons, and social media assets.

ASoudy/AGS

CRITICAL: Use for Makepad animation system. Triggers on: makepad animation, makepad animator, makepad hover, makepad state, makepad transition, "from: { all: Forward", makepad pressed, makepad 动画, makepad 状态, makepad 过渡, makepad 悬停效果

ASoudy/AGS

Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

ASoudy/AGS

Next.js App Router principles. Server Components, data fetching, routing patterns.

ASoudy/AGS

Expert integration of Supabase Auth with Next.js App Router

ASoudy/AGS

React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns.

ASoudy/AGS

Best practices for Remotion - Video creation in React

ASoudy/AGS

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

ASoudy/AGS

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

ASoudy/AGS

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

ASoudy/AGS

Three.js animation - keyframe animation, skeletal animation, morph targets, animation mixing. Use when animating objects, playing GLTF animations, creating procedural motion, or blending animations.

ASoudy/AGS

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

相關技能