当前位置: 首页 > news >正文

05-服务端渲染与元框架——10. 字体优化 - next/font

10. 字体优化 - next/font

概述

next/font 是 Next.js 内置的字体优化组件,自动优化字体加载,避免布局偏移(CLS),提升性能。支持 Google Fonts、自定义字体和系统字体。

维度内容
WhatNext.js 内置的字体优化组件
Why自动优化字体加载,避免布局偏移
When使用自定义或 Google Fonts 时
Wherelayout.js或组件中导入字体
Who需要字体优化的开发者
Howconst inter = Inter({ subsets: ['latin'] })

1. next/font 基础

1.1 Google Fonts

// app/layout.js import { Inter, Roboto, Open_Sans } from 'next/font/google'; // 单个字体 const inter = Inter({ subsets: ['latin'], display: 'swap', }); // 多个字体 const roboto = Roboto({ weight: ['400', '700'], subsets: ['latin'], display: 'swap', }); // 使用 export default function RootLayout({ children }) { return ( <html lang="zh-CN" className={inter.className}> <body>{children}</body> </html> ); }

1.2 自定义字体

// app/layout.js import localFont from 'next/font/local'; const myFont = localFont({ src: './fonts/MyFont.woff2', display: 'swap', }); // 多个字体文件 const customFont = localFont({ src: [ { path: './fonts/CustomFont-Light.woff2', weight: '300', style: 'normal', }, { path: './fonts/CustomFont-Regular.woff2', weight: '400', style: 'normal', }, { path: './fonts/CustomFont-Bold.woff2', weight: '700', style: 'normal', }, ], display: 'swap', }); export default function RootLayout({ children }) { return ( <html lang="zh-CN" className={customFont.className}> <body>{children}</body> </html> ); }

2. 字体配置

2.1 字体子集

import { Inter } from 'next/font/google'; const inter = Inter({ subsets: ['latin', 'latin-ext', 'cyrillic'], // 只加载需要的字符集 });

2.2 字体权重

import { Roboto } from 'next/font/google'; const roboto = Roboto({ weight: ['300', '400', '500', '700', '900'], subsets: ['latin'], }); // 使用不同权重 <h1 className={roboto.className}>标题</h1> // 默认 400 <p style={{ fontWeight: 700 }} className={roboto.className}>粗体</p>

2.3 字体变量

import { Inter } from 'next/font/google'; const inter = Inter({ subsets: ['latin'], variable: '--font-inter', // CSS 变量 }); export default function RootLayout({ children }) { return ( <html lang="zh-CN" className={inter.variable}> <body className="font-sans">{children}</body> </html> ); } // globals.css body { font-family: var(--font-inter); } .custom-text { font-family: var(--font-inter); font-weight: 600; }

3. 字体加载策略

3.1 display 属性

const inter = Inter({ subsets: ['latin'], display: 'swap', // 默认,使用后备字体直到自定义字体加载 // display: 'auto', // 浏览器默认 // display: 'block', // 等待字体加载,最多3秒 // display: 'fallback', // 短暂等待,然后使用后备 // display: 'optional', // 如果字体加载慢,可能永不使用 });

3.2 预加载

const inter = Inter({ subsets: ['latin'], preload: true, // 默认 true,预加载字体 });

3.3 禁用自动预加载

const inter = Inter({ subsets: ['latin'], preload: false, }); // 手动预加载 <link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossOrigin="anonymous" />

4. 完整示例

// app/layout.js import { Inter, Roboto_Mono } from 'next/font/google'; import localFont from 'next/font/local'; import './globals.css'; // Google Font const inter = Inter({ subsets: ['latin', 'latin-ext'], display: 'swap', variable: '--font-inter', }); // 等宽字体 const robotoMono = Roboto_Mono({ subsets: ['latin'], display: 'swap', variable: '--font-mono', }); // 本地字体 const headingFont = localFont({ src: [ { path: './fonts/Heading-Light.woff2', weight: '300', style: 'normal', }, { path: './fonts/Heading-Regular.woff2', weight: '400', style: 'normal', }, { path: './fonts/Heading-Bold.woff2', weight: '700', style: 'normal', }, ], variable: '--font-heading', display: 'swap', }); export const metadata = { title: '字体优化示例', description: '展示 next/font 的使用', }; export default function RootLayout({ children }) { return ( <html lang="zh-CN" className={`${inter.variable} ${robotoMono.variable} ${headingFont.variable}`} > <body className="font-sans"> {children} </body> </html> ); } // app/page.js import { Inter } from 'next/font/google'; const inter = Inter({ subsets: ['latin'] }); export default function HomePage() { return ( <div> <h1 className="text-4xl font-bold mb-4"> 字体优化示例 </h1> <p className="text-lg mb-2"> 这是使用 Inter 字体的正文。 </p> <code className="font-mono text-sm"> 这是等宽字体 </code> </div> ); } // app/blog/[slug]/page.js import { notFound } from 'next/navigation'; import { getPost } from '@/lib/posts'; export default async function BlogPostPage({ params }) { const { slug } = await params; const post = await getPost(slug); if (!post) notFound(); return ( <article className="prose prose-lg mx-auto"> <h1 className="font-heading">{post.title}</h1> <div className="font-sans">{post.content}</div> </article> ); }

5. 总结

核心要点

要点说明
Google Fonts直接导入,自动优化
本地字体使用 localFont
CSS 变量variable 选项
性能自动预加载,避免 CLS

记忆口诀

next/font 字体强,Google 本地都能装
子集权重可配置,变量类名都能用
自动优化性能好,CLS 问题不再有


6. 相关资源

  • Next.js Font 文档
  • Google Fonts
  • Web 字体优化

http://www.gsyq.cn/news/1624616.html

相关文章:

  • 专知智库 · 定义者时代的思想架构师——将企业关键资产转化为市场思想领导力
  • SpringBoot+MySQL实战:从零搭建企业级后台管理系统
  • 多模态安全审核:图像/音频内容合规检测与Agent对齐护栏
  • 【从0到1构建一个ClaudeAgent】工具与执行-Agent循环
  • 强力解锁浏览器画中画功能:告别视频观看的割裂体验
  • CI/CD 回滚演练:能发布,也要能撤回来
  • 贝叶斯优化:用高斯过程与采集函数实现智能超参数调优
  • 统一多模态Agent编排:用单一模型驱动多感官任务的可行性与边界
  • 基于HuggingFace生态的Zero_NLP项目实战指南:从Transformer模型微调到中文文本分类与NER任务的深度解析
  • Claude Code 国内安装与实战指南:AI 编程助手从零到项目集成
  • FanControl终极指南:3步搞定Windows风扇控制,告别噪音与高温
  • 企业级AI集成实战:Agent、RAG与MCP架构深度解析
  • Three.js 本地模型加载教程
  • 离线运行的 3D 模型处理工具,保密项目的稳妥选择
  • openEuler Compiler-docs技术白皮书解读:LLVM构建openEuler的完整技术方案
  • 批处理策略的数学建模:从静态 Batching 到 Continuous Batching 的吞吐分析
  • AI驱动的Three.js渲染优化:霓虹城市的智能帧率管理
  • 航天电路板为啥不能出一点错?
  • Agent越来越智能,但我发现软件工程仍然很重要
  • 【 Elasticsearch】安装配置 GitHub Copilot CLI 插件
  • 2025-6-15模拟测验
  • 从 Paper 到产品原型:只取能验证商业假设的部分
  • 跨境电商选灵爪AI开发需看真实案例与预算
  • 163MusicLyrics:如何免费获取网易云QQ音乐歌词的终极解决方案
  • 全面战争模组制作的技术解构:RPFM架构深度解析与进阶实践
  • 动态工具加载与热重载:构建 MCP Server 的插件体系及生命周期管理
  • AI 辅助前端代码生成:先给边界,再谈效率
  • MySQL 慢查询根治指南:从 EXPLAIN 看懂到索引覆盖率优化的完整链路
  • Serverless 事件流水线:自动发布不等于无人值守
  • Ollydbg逆向工程入门:从CrackMe破解实战理解程序验证逻辑