✏️

Next.jsにおけるフォントの使い方

2024/04/11に公開

Next.js App RouterでWebフォント(Google Fonts)を設定する方法をざっくりご紹介します。さらに詳しく知りたい方はドキュメントをご覧ください。
https://nextjs.org/docs/app/building-your-application/optimizing/fonts

ディレクトリ構成

myApp/
├── src/
│   └── app/
│       ├── layout.tsx
│       └── page.tsx
└── utils/
    └── fonts.ts

※必要な箇所のみ表示しています。


まずは使いたいフォントを定義しましょう。今回はNext.jsでデフォルトになっているInterを使います。どのようなスタイルでフォントを使いたいのかを指定します。

fonts.ts
import { Inter } from "next/font/google";

export const inter = Inter({
    // フォントスタイルを指定するためのオブジェクトを渡す
  subsets: ["latin"],
  display: "swap",
});

ちなみにフォントごとに指定できるスタイルを知りたい方はnode_modules/next/dist/compiled/@next/font/dist/google/index.d.tsを見てみてください。現在Next.jsで使用できるフォントが書いてあります。


次にフォントを適用させたい要素の className に先ほど定義したフォントを指定します。実は暗黙的にclassNameというプロパティが作られているんですね。興味がある方はinterの中身を覗いてみてください。

layout.tsx
import { inter } from "@/utils/fonts";

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="ja" className={`${inter.className}`}>
      <body>
        {children}
      </body>
    </html>
  );
}

フォントは、適用した要素の全ての子要素に継承されます。アプリケーション全体に適用したければ、<html>もしくは<body>に付与すればokです。


以下のようにすれば全体はinterh1だけ別のフォントにできます。

layout.tsx
import { inter, otherFont } from "@/app/fonts";

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="ja" className={`${inter.className}`}>
      <body>
        <h1 className={`${otherFont.className}`}>MyApp</h1>
        {children}
      </body>
    </html>
  );
}


以上、Webフォントの設定方法でした。

もし好みのフォントがない場合、使いたいフォントデータをダウンロードしてきてプロジェクト内に配置すればlocalフォントとして使う事もできます。また、データ最適化などについても書かれていますので是非公式ドキュメントをご覧ください。
https://nextjs.org/docs/app/building-your-application/optimizing/fonts

最後までお読みいただき、ありがとうございました!

Discussion