从零搭建 Astro + React 博客:Islands 架构实践指南
2026 年 07 月 25 日 1 分钟阅读 628 次浏览
为什么选 Astro
内容型站点的核心诉求是:首屏快、SEO 好、按需交互。Astro 的 Islands 架构天然契合——默认输出零 JS,只有真正需要交互的组件(“岛屿”)才水合。
初始化项目
pnpm create astro@latest my-blog
cd my-blog
pnpm add @astrojs/react react react-dom
pnpm add -D @tailwindcss/vite tailwindcss
在 astro.config.mjs 里启用 React 与 Tailwind:
import { defineConfig } from "astro/config";
import react from "@astrojs/react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
integrations: [react()],
vite: { plugins: [tailwindcss()] },
});
Islands 的关键:client 指令
Astro 组件默认在服务端渲染成静态 HTML。给 React 组件加 client:* 指令,才会在浏览器水合:
---
import ThemeToggle from "../components/ThemeToggle.tsx";
import Heavy from "../components/Heavy.tsx";
---
<!-- 页面加载即水合 -->
<ThemeToggle client:load />
<!-- 进入视口才水合,适合首屏以下的组件 -->
<Heavy client:visible />
常用指令:client:load(立即)、client:idle(空闲时)、client:visible(进入视口)、client:media(匹配媒体查询)。
内容系统的两种取向
- 文件驱动:MDX + Content Collections,适合纯写作、Git 管理。
- 数据库驱动:正文存库,配合后台可视化编辑,适合需要 CRUD 后台的场景。
本博客采用数据库驱动,因此后台可以直接增删改文章,而无需提交代码。
部署
Astro 支持静态导出与 SSR 两种模式。带后台管理和 API 的站点需要 SSR:
import node from "@astrojs/node";
export default defineConfig({
output: "server",
adapter: node({ mode: "standalone" }),
});
构建后 node ./dist/server/entry.mjs 即可运行;也可换成 Cloudflare / Vercel 适配器部署到边缘。
小结
Islands 架构让"高性能"和"丰富交互"不再对立。默认静态、按需水合,是内容站点在 2026 年的最优解之一。
评论区未配置
在 .env 中设置
PUBLIC_WALINE_SERVER_URL
即可启用 Waline 评论。