入门篇 - Astro内容站点搭建

知识库
知识库文档
/tech-stacks/astro/tutorial/入门篇 - Astro内容站点搭建.md

文档

Astro 内容站点搭建入门

背景

Astro 是专为内容型网站设计的框架。如果你的毕设涉及博客、文档站、作品展示、公司官网等内容为主的项目,Astro 的"默认零 JS"理念能让你获得近乎完美的 Lighthouse 分数。同时它支持混合 Vue/React/Svelte 组件——这在答辩中是非常独特的卖点。


核心概念

岛屿架构

Astro 把页面想象成海洋,交互组件是岛屿:

┌────────────────────────────┐
│  纯 HTML (海洋)            │
│                            │
│  ┌──────┐    ┌──────────┐  │
│  │ Vue  │    │  React   │  │
│  │ 岛屿 │    │  岛屿    │  │
│  └──────┘    └──────────┘  │
│                            │
│  不需要 JS 的内容完全不加载 JS │
└────────────────────────────┘

.astro 单文件组件

---
// 组件脚本(服务端执行,不会发到浏览器)
const data = await fetch('https://api.example.com/posts');
const posts = await data.json();
---

<!-- HTML 模板 -->
<h1>博客文章</h1>
{posts.map(post => <PostCard {...post} />)}

分步操作

第一步:创建项目

npm create astro@latest
# 选择 Empty 模板 + TypeScript + 安装依赖
cd my-site
npm run dev

第二步:理解路由

src/pages/
├── index.astro          → /
├── about.astro          → /about
├── blog/
│   ├── index.astro      → /blog
│   └── [slug].astro     → /blog/post-1
└── 404.astro            → 404 页面

第三步:添加框架

npx astro add react

然后就可以在 .astro 文件中使用 React 组件:

---
import Counter from '../components/Counter.jsx';
---

<Counter client:load />  <!-- client:load 表示在客户端水合 -->

第四步:Content Collections

// src/content/config.ts
import { defineCollection, z } from 'astro:content';

const blogCollection = defineCollection({
  schema: z.object({
    title: z.string(),
    date: z.date(),
    description: z.string(),
  }),
});

export const collections = { blog: blogCollection };

毕设推荐场景

作品展示站

展示毕设项目截图、技术栈、GitHub 链接。纯静态,加载快。

技术博客

记录毕设开发过程,Markdown 写作,自动生成 RSS。

多框架实验

一个页面同时用 Vue 表单 + React 图表 + Svelte 动画——展示技术广度。


思考题

  1. Astro 的岛屿架构与传统 SPA 的水合(Hydration)有什么区别?
  2. client:load vs client:visible 分别适用于什么场景?
  3. Content Collections 相比直接 import Markdown 有什么优势?

小结

Astro 是内容网站的终极方案。毕设中的作品展示、技术博客、文档页用它搭建,可以获得满分 Lighthouse 评分 + 独特的岛屿架构谈资。

信息

路径
/tech-stacks/astro/tutorial/入门篇 - Astro内容站点搭建.md
更新时间
2026/5/30