如何在Next.js的Theme UI配置中使用本地自定义字体?
前置准备
将你要使用的自定义字体文件(优先选.woff2、.woff这类压缩格式,兼容性和加载性能最优)放入项目的public/fonts目录下,没有对应目录可以自行新建。
方案1:Next.js 13+ 官方推荐方案(适配App Router/Pages Router)
使用Next.js内置的next/font能力加载本地字体,无需额外配置,自带性能优化。
- 在根入口文件中导入字体并声明CSS变量
// App Router 为例:app/layout.tsx import { ThemeUIProvider } from 'theme-ui' import localFont from 'next/font/local' import theme from './你的主题配置文件路径' // 导入CircularBlack字体 const circularBlack = localFont({ src: '../public/fonts/CircularBlack.woff2', variable: '--font-circular-black', }) // 导入fufu字体 const fufu = localFont({ src: '../public/fonts/fufu-regular.woff2', variable: '--font-fufu', }) export default function RootLayout({ children }) { return ( <html lang="zh-CN" className={`${circularBlack.variable} ${fufu.variable}`}> <body> <ThemeUIProvider theme={theme}> {children} </ThemeUIProvider> </body> </html> ) }
- 修改Theme UI主题配置,把字体值替换为对应的CSS变量即可:
// 示例:使用CircularBlack的配置 const theme = { fonts: { body: 'var(--font-circular-black), sans-serif', heading: 'var(--font-circular-black), sans-serif', monospace: 'Menlo, monospace', }, }
// 示例:使用fufu的配置 export default { fonts: { body: "var(--font-fufu), sans-serif", heading: "var(--font-fufu), sans-serif", monospace: "var(--font-fufu), sans-serif", }, styles: { root: { p: 0, m: 0, background: 'primary', cursor: 'default', position: 'relative', overflowX: "hidden", fontFamily: "body", } }, }
方案2:旧版Next.js 兼容方案(@font-face 方式)
如果你使用的是Next.js 12及更早版本,可以用传统CSS声明的方式加载字体:
- 在全局CSS文件中(比如
global.css,需要在根入口文件中引入)添加字体声明:
@font-face { font-family: 'CircularBlack'; src: url('/fonts/CircularBlack.woff2') format('woff2'), url('/fonts/CircularBlack.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; } @font-face { font-family: 'fufu'; src: url('/fonts/fufu-regular.woff2') format('woff2'), url('/fonts/fufu-regular.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; }
- 你现有的Theme UI主题配置不需要做任何修改,全局CSS生效后字体就会正常加载。
注意事项
public目录下的资源引用路径直接以/开头即可,不需要加/public前缀font-display: swap属性可以避免字体加载期间页面文字不可见,提升体验- 尽量不要使用ttf、otf这类未压缩的字体格式,会大幅增加加载耗时
内容的提问来源于stack exchange,提问作者user16993687
相关产品推荐
相关产品推荐

