项目介绍

本博客基于 Astro 4.x 构建,是一个静态站点生成(SSG)博客系统,部署在 Cloudflare Pages 上。

技术栈

  • 框架: Astro 4.7 + TypeScript
  • 样式: LESS + Open Color 色彩系统
  • 内容管理: Astro Content Collections(Markdown)
  • 部署: Cloudflare Pages(Wrangler)
  • 包管理: pnpm

项目结构

src/
├── assets/          # 静态资源(样式、图片、字体)
├── components/      # 共享组件
│   ├── BlogContext.astro   # 页面容器(Layout + SideBar)
│   ├── BlogSingle.astro    # 文章详情模板
│   ├── PostList.astro      # 文章列表组件(重构新增)
│   ├── FormattedDate.astro # 日期格式化
│   ├── GetAbstract.astro   # 摘要提取
│   ├── PageBar.astro       # 分页控件
│   ├── PostShare.astro     # 社交分享
│   └── SideBar.astro       # 侧边栏导航
├── content/         # 内容集合
│   ├── blog/        # 技术博客文章
│   ├── life/        # 生活随笔
│   ├── pages/       # 静态页面(关于)
│   └── config.ts    # 集合 Schema 定义
├── layouts/
│   └── Layout.astro # 基础 HTML 模板
├── pages/           # 路由页面
│   ├── index.astro        # 首页(博客列表)
│   ├── life.astro         # 生活随笔列表
│   ├── archive.astro      # 归档页
│   ├── link.astro         # 友链页
│   ├── about.astro        # 关于页
│   ├── rss.xml.ts         # RSS 订阅
│   ├── blog/[...slug].astro  # 博客详情
│   ├── lifes/[...slug].astro # 生活随笔详情
│   ├── page/[page].astro     # 分页
│   └── tags/[tag].astro      # 标签筛选
└── theme-simple/
    └── config.ts    # 站点配置(标题、菜单、友链等)

重构内容

这次重构主要解决了项目中积累的几个结构性问题。

1. 删除重复的内容目录

项目中同时存在 src/content/life/src/content/lifeBlog/ 两个目录,内容完全一致。统一保留 life/,删除冗余的 lifeBlog/

2. 启用 Content Collections Schema 验证

原来的 src/content/config.ts 整个被注释掉了,没有任何 schema 验证。重构后为 bloglifepages 三个集合都定义了 Zod schema:

import { defineCollection, z } from 'astro:content';

const blogSchema = z.object({
  title: z.string(),
  description: z.string(),
  pubDate: z.coerce.date(),
  heroImage: z.string().optional(),
  tags: z.array(z.string()).default([]),
});

const blog = defineCollection({ schema: blogSchema });
const life = defineCollection({ schema: blogSchema });
const pages = defineCollection({ schema: blogSchema });

export const collections = { blog, life, pages };

这样在构建时就能自动校验文章的 frontmatter 格式是否正确。

3. 修复 Collection 引用错误

src/pages/lifes/[...slug].astro 中引用的是 getCollection('lifeBlog'),但实际内容在 life/ 目录下。修正为 getCollection('life')

4. 提取共享的 PostList 组件

首页、生活页、标签页、分页页面中都有几乎一模一样的文章列表渲染逻辑。提取为 PostList.astro 组件,通过 postsbasePath 两个 props 复用:

<PostList posts={homePostAll} basePath="/blog/" />

四个页面的重复代码一下子就清爽了。

5. 修复废弃 API

about.astro 使用了 Astro 4.x 中已废弃的 getEntryBySlug(),替换为推荐的 getEntry()

6. 统一链接格式

部分页面生成的链接带有 index.html 后缀(如 /lifes/xxx/index.html),部分不带(如 /blog/xxx/)。统一为不带 index.html 的格式。

7. 修复数组操作 Bug

首页和生活页使用 .splice() 截取文章列表,这个方法会修改原数组,可能导致后续逻辑出错。改为 .slice(),不影响原数组。

8. 修复变量名拼写

homePostAlll(三个 L)修正为 homePostAll

总结

这次重构没有改变任何功能和样式,纯粹是代码质量层面的优化。构建和开发服务器均测试通过。