用 Astro 搭建我的个人网站

Astro TypeScript Web

记录从零开始用 Astro 4 构建个人网站的过程,包括项目结构设计、Tailwind CSS 配置以及部署到 VPS 的完整流程。


为什么选择 Astro?

Astro 是一个现代的静态网站框架,特别适合构建性能优先的网站。与传统的 React 或 Vue 应用不同,Astro 默认不发送 JavaScript 到浏览器。

核心优势

  • 零 JavaScript:默认情况下,Astro 生成纯 HTML/CSS
  • Islands Architecture:需要交互的部分再加入 React/Vue 等框架
  • SEO 友好:静态生成的 HTML 对搜索引擎友好
  • 快速加载:小的初始加载体积,快速的首屏展示

项目结构

frontend/
├── src/
│   ├── pages/       # 页面目录,自动生成路由
│   ├── components/  # 可复用组件
│   ├── layouts/     # 页面模板
│   ├── content/     # 内容文件(博客、文档等)
│   └── styles/      # 全局样式
└── astro.config.mjs # Astro 配置文件

每个 .astro.md 文件在 pages/ 下都会自动生成对应的路由。

集成 React Islands

某些页面需要交互功能(如 AI 对话、图片生成),我们可以在 Astro 页面中嵌入 React 组件:

---
import MyReactComponent from '../components/MyComponent.tsx';
---

<MyReactComponent client:load />

client:load 指令告诉 Astro 在页面加载时立即加载这个 React 组件。

Tailwind CSS 集成

使用 @tailwindcss/vite 插件在 Astro 中使用 Tailwind CSS:

// astro.config.mjs
export default defineConfig({
  vite: {
    plugins: [tailwindcss()],
  },
});

部署到 VPS

完整的部署流程包括:

  1. 本地构建:npm run build 生成 dist/ 目录
  2. 上传到 VPS
  3. 配置 Nginx 反向代理
  4. 配置 SSL 证书

最后确保 Nginx 配置正确指向 dist/ 目录,就可以享受高性能的静态网站了。


这只是开始,后续可以继续完善博客功能、评论系统、CDN 加速等。