Communitygithub.com

ASoudy/AGS

使用 Astro 构建内容驱动的网站——默认零 JavaScript、孤岛架构、多框架组件,并支持 Markdown/MDX。

AGS 是什么?

Astro 是一个专为内容密集型网站(博客、文档、作品集、营销页面、电商)设计的 Web 框架。它的核心创新是「孤岛架构」:默认情况下,Astro 不向浏览器发送任何 JavaScript,只有交互式组件会按需选择性水合,形成一个个独立的「孤岛」。该技能支持在同一项目中同时使用 React、Vue、Svelte、Solid 等多种 UI 框架,让开发者能为每个组件选择最合适的工具。Astro 提供了文件路由、内容集合(类型安全的 Markdown/MDX 管理)、自动 CSS 作用域、灵活的 SSG/SSR 模式等特性,特别适合对性能与 Core Web Vitals 要求极高的项目。

兼容平台✓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 = '我的 Astro 网站' } = Astro.props;
---

<html lang="zh-CN">
  <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="关于我们">
  <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 前置元数据里放入机密信息
  • ❌ 在静态模式下不要跳过动态路由的 getStaticPaths——构建过程会失败

安全与注意事项

  • .astro 文件中的前置元数据代码仅在服务器端运行,不会暴露给浏览器。
  • 仅将 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——没有自动补全 解决方案: 在前置元数据中定义 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.

相关技能