Astro 有哪些性能优化策略?如何构建超快速的 Astro 网站?
Astro 提供了多种性能优化策略和技术,帮助开发者构建超快速的网站。了解这些优化技巧对于构建高性能的 Astro 应用至关重要。核心性能优化策略:零 JavaScript 默认:Astro 默认只输出纯 HTML只在需要时才加载 JavaScript显著减少初始加载时间岛屿架构优化:只为交互式组件添加 client:* 指令使用合适的 client:* 指令类型延迟非关键交互的水合代码分割和懒加载:---// 延迟加载组件import { lazy } from 'astro';const HeavyComponent = lazy(() => import('../components/HeavyComponent.jsx'));---<HeavyComponent client:visible />图片优化:---import { Image } from 'astro:assets';import heroImage from '../assets/hero.jpg';---<!-- 使用正确的格式和尺寸 --><Image src={heroImage} alt="Hero" widths={[400, 800, 1200, 1600]} sizes="(max-width: 768px) 100vw, 50vw" formats={['avif', 'webp', 'jpeg']} loading="eager" priority={true}/><!-- 懒加载非关键图片 --><Image src={image} alt="Gallery Image" loading="lazy" decoding="async"/>CSS 优化:---// 使用作用域样式---<style> /* 作用域样式,不会影响其他组件 */ .container { max-width: 1200px; margin: 0 auto; }</style><style is:global> /* 全局样式,谨慎使用 */ body { font-family: system-ui, sans-serif; }</style>预加载关键资源:---// src/layouts/Layout.astro---<html> <head> <!-- 预加载关键 CSS --> <link rel="preload" href="/styles/critical.css" as="style" /> <!-- 预加载字体 --> <link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin /> <!-- 预连接到外部域名 --> <link rel="preconnect" href="https://api.example.com" /> <!-- DNS 预解析 --> <link rel="dns-prefetch" href="https://cdn.example.com" /> </head> <body> <slot /> </body></html>数据获取优化:---// src/pages/blog/[slug].astroimport { getEntry } from 'astro:content';// 并行获取数据const [post, relatedPosts, comments] = await Promise.all([ getEntry('blog', Astro.params.slug), fetchRelatedPosts(Astro.params.slug), fetchComments(Astro.params.slug),]);// 使用缓存const cachedData = await cache.get(`post:${Astro.params.slug}`);if (cachedData) { return cachedData;}const data = await fetchData();await cache.set(`post:${Astro.params.slug}`, data, { ttl: 3600 });---<h1>{post.data.title}</h1><Content />构建优化:// astro.config.mjsimport { defineConfig } from 'astro/config';export default defineConfig({ build: { // 优化构建输出 inlineStylesheets: 'auto', }, vite: { build: { // 代码分割 rollupOptions: { output: { manualChunks: { vendor: ['react', 'react-dom'], utils: ['lodash', 'date-fns'], }, }, }, }, },});服务端渲染优化:// src/middleware.tsexport const onRequest = async (context, next) => { // 添加缓存头 const response = await next(); // 为静态资源添加长期缓存 if (context.url.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg)$/)) { response.headers.set('Cache-Control', 'public, max-age=31536000, immutable'); } // 为 API 响应添加短期缓存 if (context.url.pathname.startsWith('/api/')) { response.headers.set('Cache-Control', 'public, max-age=60'); } return response;};使用适配器优化部署:// astro.config.mjsimport { defineConfig } from 'astro/config';import vercel from '@astrojs/vercel/server';export default defineConfig({ output: 'server', adapter: vercel({ // Vercel 特定优化 imageService: true, edgeMiddleware: true, }),});性能监控和分析:// src/lib/performance.tsexport function measurePerformance(name: string, fn: () => Promise<void>) { return async () => { const start = performance.now(); await fn(); const duration = performance.now() - start; console.log(`${name} took ${duration.toFixed(2)}ms`); };}// 使用export async function GET(context) { await measurePerformance('data-fetch', async () => { const data = await fetchData(); return new Response(JSON.stringify(data)); });}Web Vitals 优化:---// src/layouts/Layout.astro---<html> <head> <script> // 监控 Core Web Vitals import { onCLS, onFID, onFCP, onLCP, onTTFB } from 'web-vitals'; onCLS(console.log); onFID(console.log); onFCP(console.log); onLCP(console.log); onTTFB(console.log); </script> </head> <body> <slot /> </body></html>减少第三方脚本:---// 延迟加载分析脚本---<script> // 只在生产环境加载 if (import.meta.env.PROD) { window.addEventListener('load', () => { const script = document.createElement('script'); script.src = 'https://analytics.example.com/script.js'; script.async = true; document.head.appendChild(script); }); }</script>使用 Service Worker 缓存:// public/sw.jsconst CACHE_NAME = 'astro-v1';const urlsToCache = ['/', '/styles/main.css'];self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => cache.addAll(urlsToCache)) );});self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => response || fetch(event.request)) );});---// 注册 Service Worker---<script> if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/sw.js'); }); }</script>性能优化清单:构建时优化:启用代码分割压缩和优化资源使用 Tree Shaking优化图片和字体运行时优化:使用合适的 client:* 指令实现懒加载优化数据获取使用缓存策略网络优化:使用 CDN启用压缩(gzip、brotli)优化 HTTP 请求使用 HTTP/2 或 HTTP/3渲染优化:减少重绘和回流使用 CSS 动画而非 JavaScript优化 DOM 结构避免强制同步布局性能测试工具:LighthouseWebPageTestChrome DevTools PerformanceAstro 内置的构建分析Astro 的性能优化策略可以帮助你构建超快速的网站,提供优秀的用户体验和 SEO 表现。