# Astro Web 框架
## 概述
Astro 是一个专为内容丰富的网站(如博客、文档、作品集、营销站点和电子商务)设计的 Web 框架。其核心创新是**群岛架构 (Islands Architecture)**:默认情况下,Astro 不会向浏览器发送任何 JavaScript。交互式组件被选择性地作为独立的“岛屿”进行水合。Astro 支持在同一个项目中同时使用 React、Vue、Svelte、Solid 等 UI 框架,让你能为每个组件选择最合适的工具。
## 何时使用此技能
- 构建博客、文档站点、营销页面或作品集时
- 性能和核心 Web 指标 (Core Web Vitals) 是首要任务时
- 项目包含大量 Markdown 或 MDX 文件时
- 需要 SSG(静态)输出,并可选择 SSR 用于动态路由时
- 用户询问关于 `.astro` 文件、`Astro.props`、内容集合 (Content Collections) 或 `client:` 指令时
## 工作原理
### 第 1 步:项目设置
bash
npm create astro@latest my-site
cd my-site
npm install
npm run dev
根据需要添加集成:
bash
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` 文件顶部包含一个代码围栏(仅限服务器端),下方是模板:
astro
---
// src/components/Card.astro
// 此代码块仅在服务器端运行 — 绝不会在浏览器中运行
interface Props {
title: string;
href: string;
description: string;
}
const { title, href, description } = Astro.props;
---
{description}
/* 自动作用域限定到此组件 */
.card { border: 1px solid #eee; padding: 1rem; }
### 第 3 步:基于文件的页面和路由
src/pages/index.astro → /
src/pages/about.astro → /about
src/pages/blog/[slug].astro → /blog/:slug (动态)
src/pages/blog/[...path].astro → /blog/* (全匹配)
Dyna