文档
Astro 个人博客站
目标
用 Astro 搭建一个最小博客站,展示 .astro 组件、Markdown 内容集合和岛屿架构。
完整代码
1. 项目结构
my-blog/
├── astro.config.mjs
├── src/
│ ├── pages/
│ │ └── index.astro
│ ├── content/
│ │ └── posts/
│ │ ├── post-1.md
│ │ └── post-2.md
│ └── components/
│ └── PostCard.astro
2. src/content/posts/post-1.md
---
title: '毕设选题心得'
date: 2024-03-15
description: '如何选择一个合适的毕业设计题目'
---
## 选题三原则
1. **兴趣驱动**:选你真正感兴趣的方向
2. **技术可行**:确保技术栈在掌握范围内
3. **答辩加分**:有可视化展示(前端/图表/3D)
我在选题时最终选择了基于 Three.js 的校园 3D 导览系统,既有趣又能展示技术能力。
3. src/content/posts/post-2.md
---
title: 'Astro 入门指南'
date: 2024-04-01
description: '了解 Astro 岛屿架构和内容优先理念'
---
## 什么是岛屿架构?
Astro 默认在服务端渲染 HTML,只有需要交互的组件才会在客户端"水合"(hydrate)。
```astro
<!-- 这个组件在页面加载后立即水合 -->
<Counter client:load />
<!-- 这个组件仅当滚动到可见区域时才水合 -->
<Chart client:visible />
### 4. `src/components/PostCard.astro`
```astro
---
interface Props {
title: string;
date: string;
description: string;
slug: string;
}
const { title, date, description, slug } = Astro.props;
---
<article class="card">
<h2><a href={`/posts/${slug}`}>{title}</a></h2>
<time>{date}</time>
<p>{description}</p>
</article>
<style>
.card {
background: white;
padding: 20px;
border-radius: 12px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
transition: transform 0.2s;
}
.card:hover { transform: translateY(-2px); }
.card h2 { margin: 0 0 8px; }
.card h2 a { color: #1e293b; text-decoration: none; }
.card time { color: #94a3b8; font-size: 0.9em; }
.card p { color: #475569; margin-top: 8px; }
</style>
5. src/pages/index.astro
---
import PostCard from '../components/PostCard.astro';
// 模拟从 Content Collections 获取(实际用 getCollection)
const posts = [
{ slug: 'post-1', data: { title: '毕设选题心得', date: '2024-03-15', description: '如何选择一个合适的毕业设计题目' } },
{ slug: 'post-2', data: { title: 'Astro 入门指南', date: '2024-04-01', description: '了解 Astro 岛屿架构和内容优先理念' } },
];
---
<html lang="zh">
<head>
<meta charset="utf-8" />
<title>我的技术博客</title>
</head>
<body>
<header>
<h1>🚀 我的技术博客</h1>
<p class="subtitle">记录毕设开发的心得与收获</p>
</header>
<main>
{
posts.map((post) => (
<PostCard
title={post.data.title}
date={post.data.date}
description={post.data.description}
slug={post.slug}
/>
))
}
</main>
<footer>
<p>Built with Astro · 零 JS 博客</p>
</footer>
</body>
</html>
<style is:global>
body {
font-family: system-ui;
background: #f8fafc;
max-width: 680px;
margin: 0 auto;
padding: 20px;
}
header {
text-align: center;
padding: 40px 0;
}
header h1 { margin: 0; font-size: 2.2em; }
.subtitle { color: #64748b; }
footer {
text-align: center;
color: #94a3b8;
padding: 30px 0;
font-size: 0.9em;
}
</style>
运行步骤
npm create astro@latest astro-blog -- --template minimal
cd astro-blog
npm run dev
预期输出
- 博客首页展示 2 篇文章卡片
- 页面完全静态 HTML(查看源码无 JS!)
- 卡片 hover 有上浮动画
- 这是零 JS 页面,加载速度极快