You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中如何跨页面复用@next/font/google导入的多种字体?

使用@next/font/google跨页面复用字体并绑定选择器的方案

1. 全局字体配置(避免重复加载)

创建专门的字体配置文件(比如src/styles/fonts.js),集中管理所有需要的Google字体,Next.js会自动处理自托管与缓存,确保字体仅加载一次:

// src/styles/fonts.js
import { Exo_2, Roboto, Open_Sans } from '@next/font/google';

// 配置字体,按需指定字重、样式、子集
export const exo2 = Exo_2({
  subsets: ['latin'],
  weight: ['400', '700'],
  style: ['normal', 'italic'],
  variable: '--font-exo2', // 定义CSS变量用于全局引用
});

export const roboto = Roboto({
  subsets: ['latin'],
  weight: ['300', '500'],
  variable: '--font-roboto',
});

export const openSans = Open_Sans({
  subsets: ['latin'],
  weight: ['400'],
  variable: '--font-opensans',
});

2. 全局布局注入字体

在Next.js的全局布局文件中注入字体变量,让所有页面和组件都能访问:

App Router 版本(src/app/layout.js)

import { exo2, roboto, openSans } from '@/styles/fonts';
import './globals.css';

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN" className={`${exo2.variable} ${roboto.variable} ${openSans.variable}`}>
      <body>{children}</body>
    </html>
  );
}

Pages Router 版本(src/pages/_app.js)

import { exo2, roboto, openSans } from '@/styles/fonts';
import '../styles/globals.css';

export default function MyApp({ Component, pageProps }) {
  return (
    <div className={`${exo2.variable} ${roboto.variable} ${openSans.variable}`}>
      <Component {...pageProps} />
    </div>
  );
}

3. 绑定字体到特定选择器

在全局CSS文件(比如globals.css)中,用CSS变量将字体绑定到HTML标签或自定义类:

/* src/app/globals.css 或 src/styles/globals.css */
/* 绑定到HTML标签 */
h1 {
  font-family: var(--font-exo2), sans-serif;
  font-weight: 700;
}

p {
  font-family: var(--font-roboto), sans-serif;
  font-weight: 300;
}

/* 绑定到自定义类 */
.text-opensans {
  font-family: var(--font-opensans), sans-serif;
}

.bold-italic-exo2 {
  font-family: var(--font-exo2), sans-serif;
  font-weight: 700;
  font-style: italic;
}

4. 跨页面/组件复用

在任意页面(比如about.js)或组件中,直接使用对应的标签或类名即可,无需重复导入字体:

// src/app/about/page.js 或 src/pages/about.js
export default function AboutPage() {
  return (
    <div>
      <h1>关于我们</h1> {/* 自动使用Exo 2字体 */}
      <p>这是关于页面的介绍文本,使用Roboto字体</p>
      <div className="text-opensans">这段文字使用Open Sans字体</div>
      <div className="bold-italic-exo2">这段是加粗斜体的Exo 2字体</div>
    </div>
  );
}

关键说明

  • 字体在构建时仅下载一次,与静态资源一同自托管,浏览器不会向Google发送请求,兼顾性能与隐私。
  • 通过CSS变量实现全局引用,避免在每个组件中重复导入字体实例。
  • 若仅需局部使用某字体,也可直接在组件内导入字体实例,通过className={font.className}使用,但全局配置更适合跨页面复用场景。

内容的提问来源于stack exchange,提问作者Anushka Chauhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:20:39