Astro 支持多种渲染模式,可以根据不同的使用场景选择最适合的渲染策略。理解这些渲染模式对于构建高性能的 Astro 应用至关重要。
主要渲染模式:
-
静态生成(Static Generation - SSG):
- 默认模式
- 在构建时生成 HTML
- 适合内容不经常变化的页面
- 性能最佳,SEO 友好
astro// src/pages/index.astro --- const posts = await fetch('https://api.example.com/posts').then(r => r.json()); --- <h1>博客文章</h1> {posts.map(post => ( <article> <h2>{post.title}</h2> <p>{post.excerpt}</p> </article> ))} -
服务端渲染(Server-Side Rendering - SSR):
- 每次请求时动态生成 HTML
- 适合需要实时数据的页面
- 需要配置适配器(Adapter)
javascript// astro.config.mjs import { defineConfig } from 'astro/config'; import vercel from '@astrojs/vercel/server'; export default defineConfig({ output: 'server', adapter: vercel(), });astro// src/pages/dashboard.astro --- // 每次请求都会执行 const user = await getUserFromSession(Astro.request); const data = await fetchUserData(user.id); --- <h1>欢迎, {user.name}</h1> <p>你的数据: {data}</p> -
混合渲染(Hybrid Rendering):
- 结合静态和动态渲染
- 可以为不同页面指定不同的渲染模式
- 提供最大的灵活性
javascript// astro.config.mjs import { defineConfig } from 'astro/config'; import vercel from '@astrojs/vercel/server'; export default defineConfig({ output: 'hybrid', adapter: vercel(), });astro// src/pages/static.astro --- // 静态页面 export const prerender = true; --- <h1>静态页面</h1>astro// src/pages/dynamic.astro --- // 动态页面 export const prerender = false; --- <h1>动态页面</h1> -
客户端渲染(Client-Side Rendering):
- 使用
client:only指令 - 完全在浏览器中渲染
- 适合需要大量客户端交互的组件
astro--- import InteractiveChart from '../components/InteractiveChart.jsx'; --- <InteractiveChart client:only="react" /> - 使用
预渲染(Prerender)配置:
astro--- // 控制单个页面的预渲染行为 export const prerender = true; // 静态生成 export const prerender = false; // 服务端渲染 export const prerender = 'auto'; // 自动判断 ---
动态路由:
astro--- // src/pages/blog/[id].astro export async function getStaticPaths() { const posts = await fetch('https://api.example.com/posts').then(r => r.json()); return posts.map(post => ({ params: { id: post.id }, props: { post }, })); } const { id } = Astro.params; const { post } = Astro.props; --- <h1>{post.title}</h1> <p>{post.content}</p>
适配器(Adapters):
适配器将 Astro 项目部署到不同的平台:
bash# Vercel npx astro add vercel # Netlify npx astro add netlify # Cloudflare npx astro add cloudflare # Node.js npx astro add node
javascript// astro.config.mjs import { defineConfig } from 'astro/config'; import vercel from '@astrojs/vercel/server'; import netlify from '@astrojs/netlify/edge'; import cloudflare from '@astrojs/cloudflare'; export default defineConfig({ output: 'server', adapter: vercel(), // 或 netlify(), cloudflare() });
选择渲染模式的指南:
-
使用静态生成(SSG):
- 博客文章
- 文档页面
- 营销页面
- 内容不经常变化的页面
-
使用服务端渲染(SSR):
- 用户仪表板
- 需要认证的页面
- 实时数据展示
- 个性化内容
-
使用混合渲染:
- 大部分内容静态,部分动态
- 需要灵活性的大型应用
- 既有公开页面又有私有页面的应用
-
使用客户端渲染:
- 复杂的交互式组件
- 需要大量客户端状态管理
- 不需要 SEO 的功能
性能优化技巧:
- 默认使用静态生成
- 只为需要动态内容的页面启用 SSR
- 使用
client:*指令控制水合时机 - 利用混合渲染平衡性能和功能
- 合理使用适配器优化部署
理解 Astro 的渲染模式可以帮助你构建既快速又灵活的 Web 应用。