SSR/SSG:Next.js、Nuxt.js的SEO优化与缓存策略
SSR/SSG 框架的 SEO 优化策略
Next.js (React)
使用
next/head
动态管理 meta 标签:import Head from 'next/head'; function Page() {return (<Head><title>Custom Page Title</title><meta name="description" content="SEO-friendly description" /><meta property="og:title" content="Social Media Title" /></Head>); }
通过
getStaticProps
生成静态路径(SSG):export async function getStaticPaths() {return {paths: [{ params: { id: '1' } }, { params: { id: '2' } }],fallback: false}; }
Nuxt.js (Vue)
内置
nuxt.config.js
全局 SEO 配置:export default {head: {titleTemplate: '%s - My Site',meta: [{ charset: 'utf-8' },{ name: 'viewport', content: 'width=device-width' }]} }
页面级 SEO 覆盖:
export default {head() {return {title: 'Dynamic Page Title',meta: [{ hid: 'description', name: 'description', content: 'Page-specific description' }]}} }
缓存策略实现
Next.js 缓存控制
静态资源缓存(通过
next.config.js
):module.exports = {async headers() {return [{source: '/_next/static/(.*)',headers: [{key: 'Cache-Control',value: 'public, max-age=31536000, immutable'}]}];} };
ISR (Incremental Static Regeneration):
export async function getStaticProps() {return {props: {},revalidate: 60 // 每60秒重新生成}; }
Nuxt.js 缓存方案
组件级缓存(需安装
@nuxtjs/component-cache
):export default {render: {bundleRenderer: {cache: require('lru-cache')({max: 1000,maxAge: 1000 * 60 * 15})}} }
CDN 缓存头设置:
export default {render: {cdn: {cacheControl: 'public, max-age=3600, s-maxage=3600'}} }
性能优化补充
Next.js 关键优化
动态导入减少首屏负载:
import dynamic from 'next/dynamic'; const HeavyComponent = dynamic(() => import('../components/Heavy'));
预加载关键资源:
<Head><link rel="preload" href="/font.woff2" as="font" crossOrigin="" /> </Head>
Nuxt.js 性能技巧
自动生成 sitemap(需安装
@nuxtjs/sitemap
):export default {modules: ['@nuxtjs/sitemap'],sitemap: {hostname: 'https://example.com',gzip: true} }
图片优化(通过
@nuxt/image
):export default {modules: ['@nuxt/image'],image: {domains: ['cdn.example.com']} }
监控与调试
通用方案
- 使用
next-axiom
或@nuxtjs/sentry
进行错误跟踪 - Lighthouse CI 集成检查 SEO 评分
- 通过
next build --analyze
或nuxt build --analyze
分析包大小
以上实现需根据实际项目需求调整缓存时间和 SEO 元数据,建议配合 CI/CD 流程实现自动化部署和缓存失效策略。