教程 ·
Astro 快速入门指南
从零开始学习 Astro 框架,了解其核心概念、组件系统、内容集合和静态生成能力。
Astro 快速入门指南
Astro 是一个专注于内容的现代前端框架,以”默认零 JavaScript”著称,非常适合构建博客、文档和营销网站。
为什么选择 Astro
岛屿架构(Islands Architecture)
Astro 采用革命性的岛屿架构:页面大部分是静态 HTML,只有需要交互的部分(“岛屿”)才加载 JavaScript。
这意味着:
- 极快的加载速度:静态 HTML 无需 JS 解析
- 按需加载:只在需要时加载交互组件
- 框架无关:可以混用 React、Vue、Svelte
内容集合
Astro 的内容集合提供了类型安全的内容管理:
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
const blog = defineCollection({
schema: z.object({
title: z.string(),
date: z.coerce.date(),
tags: z.array(z.string()),
}),
});
export const collections = { blog };
安装与配置
创建项目
# 使用官方 CLI 创建项目
npm create astro@latest my-site
# 进入项目目录
cd my-site
# 启动开发服务器
npm run dev
添加集成
Astro 通过集成扩展功能:
# 添加 React 支持
npx astro add react
# 添加 Tailwind CSS
npx astro add tailwind
# 添加 MDX 支持
npx astro add mdx
目录结构
my-site/
├── src/
│ ├── components/ # 可复用组件
│ ├── layouts/ # 页面布局
│ ├── pages/ # 页面文件(路由基于文件系统)
│ └── content/ # 内容集合
├── public/ # 静态资源
└── astro.config.mjs # 配置文件
Astro 组件
基本语法
Astro 组件使用 .astro 扩展名,由 frontmatter 脚本和模板组成:
---
// frontmatter 脚本(服务端执行)
const { title, date } = Astro.props;
const formattedDate = date.toLocaleDateString('zh-CN');
---
<!-- HTML 模板 -->
<article>
<h1>{title}</h1>
<time>{formattedDate}</time>
<slot /> <!-- 插槽:子内容占位 -->
</article>
Props 类型定义
---
interface Props {
title: string;
date: Date;
tags?: string[];
}
const { title, date, tags = [] } = Astro.props;
---
使用客户端 JavaScript
使用 client:* 指令激活组件的 JavaScript:
---
import Counter from './Counter.jsx';
---
<!-- 页面加载时立即激活 -->
<Counter client:load />
<!-- 浏览器空闲时激活 -->
<Counter client:idle />
<!-- 进入视口时激活 -->
<Counter client:visible />
内容集合与动态路由
获取文章列表
---
import { getCollection } from 'astro:content';
const posts = await getCollection('blog', ({ data }) => {
return !data.draft; // 过滤草稿
});
// 按日期排序
posts.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>
</li>
))}
</ul>
动态路由
---
// src/pages/blog/[...slug].astro
import { getCollection } from 'astro:content';
import type { GetStaticPaths } from 'astro';
export const getStaticPaths: GetStaticPaths = async () => {
const posts = await getCollection('blog');
return posts.map(post => ({
params: { slug: post.slug },
props: { post },
}));
};
const { post } = Astro.props;
const { Content } = await post.render();
---
<Content />
构建与部署
# 构建生产版本
npm run build
# 预览构建结果
npm run preview
构建完成后,dist/ 目录包含所有静态文件,可以部署到任何静态托管服务:Vercel、Netlify、GitHub Pages 等。
总结
Astro 是构建内容为主网站的绝佳选择。它的岛屿架构确保了优秀的性能,内容集合提供了类型安全,丰富的集成生态让你可以使用熟悉的工具。如果你正在考虑搭建博客或文档站,Astro 值得一试。