使用 Astro 构建静态博客
为什么选择 Astro?
Astro 是一个现代化的静态网站生成器,它具有以下特点:
- 零 JavaScript 默认
- 支持多种框架组件(React、Vue、Svelte等)
- 优秀的开发体验
- 极快的构建速度
- 良好的 SEO 支持
项目结构
src/
├── components/ # 可复用组件
│ ├── PostList.astro # 文章列表组件
│ ├── NoteList.astro # 笔记列表组件
│ └── TagList.astro # 标签列表组件
├── content/ # 内容文件(Markdown)
│ ├── blog/ # 博客文章
│ └── notes/ # 笔记内容
├── layouts/ # 页面布局
│ ├── BaseLayout.astro # 基础布局
│ ├── BlogPostLayout.astro # 博客文章布局
│ └── NoteLayout.astro # 笔记布局
├── pages/ # 路由页面
│ ├── [slug].astro # 文章详情页
│ ├── category/ # 分类页面
│ ├── tag/ # 标签页面
│ ├── notes/ # 笔记相关页面
│ ├── archive.astro # 归档页面
│ ├── about.astro # 关于页面
│ └── index.astro # 首页
└── styles/ # 全局样式
主要功能实现
1. 内容管理
使用 Astro 的内容集合(Content Collections)管理博客文章和笔记:
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
const blogCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.string(),
category: z.string().optional(),
tags: z.array(z.string()).optional()
})
});
const noteCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.string(),
category: z.string().optional(),
tags: z.array(z.string()).optional()
})
});
2. 路由结构
博客采用扁平化的路由结构:
/
- 首页,显示最新文章列表/[slug]
- 文章详情页/category/[category]
- 分类页面/tag/[tag]
- 标签页面/archive
- 文章归档页面/notes
- 笔记列表页面/notes/[slug]
- 笔记详情页面/about
- 关于页面
3. 主题切换
实现了一个简单的深色模式切换功能,使用 CSS 变量和 localStorage:
function toggleTheme() {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
document.documentElement.setAttribute('data-theme', isDark ? 'light' : 'dark');
localStorage.setItem('theme', isDark ? 'light' : 'dark');
}
4. 响应式设计
使用 CSS 媒体查询实现响应式布局:
@media (max-width: 640px) {
body {
padding: 1rem;
}
h1 {
font-size: 1.5rem;
}
}
部署
项目可以部署到多个平台:
- Vercel
- Cloudflare Pages
- Netlify
后续优化计划
- 添加文章目录
- 实现文章搜索
- 添加评论系统
- 优化图片加载
- 添加更多交互功能