🔖

Next.js(App Router)、TailwindCSSでGoogle Fontsを使うときの手順メモ

2024/02/26に公開

Overview

App Router環境下でGoogle Fontsを利用する場合、Next.js公式が用意しているAPIを使用します。直接フォントファイルをローカル(サーバー内)に保存してそこから利用する方法もありますが、本記事では取り扱いません。詳細については公式のドキュメントに記載がありました(2024年2月25日現在)ので、そちらをご確認ください。

公式
https://nextjs.org/docs/app/building-your-application/optimizing/fonts

こちらの記事で簡単にまとめられていましたので、簡単に確認したい方はどうぞ
https://zenn.dev/hayato94087/articles/f6557abbd6d079

大まかな流れ

  • フォント用のAPIを使用してCSSで使用する変数を定義する
  • フォントを使う場所を決める
  • 変数をインポートして使用する

手順

  • Step.1 変数の定義
    フォント用のAPIを使用してCSSで使用する変数を定義する

  • Step.2 使用場所の決定
    フォントを使う場所(範囲)を決める

  • Step.3 インポートして使用
    変数をインポートして使用する

  • おまけ:フォントの使用場所とインスタンス生成について

Step.1 変数の定義

任意のファイルに変数を定義します。
後述のStep.2と関係する内容ですが、アプリケーション全体で利用するのであればsrc/app/layout.tsxに宣言してそのまま使ったほうが良さそうですね。

import { BIZ_UDGothic } from "next/font/google";

export const biz_udGothic400 = BIZ_UDGothic({
  subsets: ["latin"],
  weight: "400",
  variable: "--font-biz-udgothic400",
  display: "swap",
});

export const biz_udGothic700 = BIZ_UDGothic({
  subsets: ["latin"],
  weight: "700",
  variable: "--font-biz-udgothic700",
  display: "swap",
});

なお、importするときの名称はhttps://fonts.google.com/selection/embedのCSS classesの"font-family"プロパティから分かります。

.biz-udgothic-regular {
  font-family: "BIZ UDGothic", sans-serif;
  font-weight: 400;
  font-style: normal;
}

.biz-udgothic-bold {
  font-family: "BIZ UDGothic", sans-serif;
  font-weight: 700;
  font-style: normal;
}

Step.2 使用場所の決定

使いたい範囲にフォントを導入します。
インポートされた範囲で使用できる仕組みなので、、

アプリケーション全体で使用したい場合はsrc/app/layout.tsx(root layout)に
そのルーティング配下で使用したい場合はsrc/app/パス名/layout.tsx(layout)に
そのページだけで使用したい場合はsrc/app/パス名/pages.tsx(unique page)に

App Routerのlayoutの仕組みを理解していたら「まぁそうでしょうね」程度の仕様なので、特段注意するところもなさそうです。

公式ドキュメントではfonts#preloadingで説明されています。

1つのアプリケーション内でいくつもフォントを使わないであろうことを考えるとsrc/app/layout.tsxに入れておけば良さそうではあります。

(公式ドキュメントに記載されていますが)念のために補足をしておくと、複数のフォントを使用するということは、それだけクライアントのリソースを使用することになるため、保守的であるべき(控えめにあるべき)です。

Recommendation: Use multiple fonts conservatively since each new font is an additional resource the client has to download.

Step.3 インポートして使用

今回はアプリケーション全体に適用したいのでRoot Layoutでインポートして使用します。

import { biz_udGothic400, biz_udGothic700 } from "../../utils/fonts/fonts";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  console.log("RootLayout");

  return (
    <html
      lang='ja'
      className={`${biz_udGothic400.className}`}
    >
      <Head children={undefined}></Head>
      <body>
        <main>{children}</main>
      </body>
    </html>
  );
}

おまけ:フォントの使用場所とインスタンス生成について

まんま公式ドキュメントの翻訳ですが、、

Next.jsで用意しているlocalFont用の関数、Google font用の関数のどちらにおいても、呼ばれるたびに新しいインスタンスを生成する仕組みとなっています。同じようなインスタンスがいくつも生成されてしまうことは単純に無駄なので、「単一の共有されるファイルで関数をロードする」「インスタンスをconstantとしてエクスポートする」「使いたい場所でconstantをインポートする」ことが推奨されています。

Every time you call the localFont or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted. In this situation, it is recommended to do the following:

  • Call the font loader function in one shared file
  • Export it as a constant
  • Import the constant in each file where you would like to use this font

Discussion