1. /
  2. WEB知識
  3. /
  4. Next.jsでGoogle Fontsを使用のが便利すぎる

Next.jsでGoogle Fontsを使用のが便利すぎる

Next.jsでGoogle Fontsを使用のが便利すぎる

最近はNext.jsでWEB開発をしていて、改めてその便利さを実感しています。特に、Google Fontsを簡単に利用できる点が大きな理由の一つです。

Google Fonts

WEB制作の際によく利用するのが、無料で使えるGoogle Fontsです。Next.jsでの導入方法は非常に簡単で、next/font/googleからフォントを関数としてインポートするだけでGoogle Fontsを利用できます。さらに、ブラウザからGoogleにリクエストが送信されないため、パフォーマンスが低下しない点もメリットです。

使用方法

フォントはNext.jsに標準で含まれているため、基本的にはインストール不要ですが、もし含まれていない場合は、まずインストールしましょう。

npm install @next/font

使い方はとてもシンプルです。

  1. next/font/googleから使いたいフォントをインポート
  2. インポートしたフォントを定義
  3. クラス名にフォントを指定して利用

サイト全体に使用

インポートしたフォントを変数として定義し、<body>要素全体に適用することもできます。

import { Manrope, Noto_Sans_TC } from 'next/font/google';

const manropeSans = Manrope({
  variable: '--font-manrope-sans',
  subsets: ['latin'],
});

const notoSansTC = Noto_Sans_TC({
  variable: '--font-noto_sans_tc',
  subsets: ['latin'],
});

// ...他のコード

export default function RootLayout({ children }) {
  return (
    <body
      className={`${manropeSans.variable} ${notoSansTC.variable} antialiased bg-white`}
      data-scroll-behavior='smooth'
    >
      {children}
    </body>
  );
}

特定の箇所に使用

例えば、ヘッダーのロゴだけ異なるフォントを使いたい場合は、そのロゴ部分だけ個別に適用することも可能です。
公式ではvariable fontsの使用を推奨していますが、variable対応していないフォントについては、weightで指定できます。

import { Manrope, Noto_Sans_TC } from 'next/font/google';

const manropeSans = Manrope({
  variable: '--font-manrope-sans',
  subsets: ['latin'],
});

const notoSansTC = Noto_Sans_TC({
  variable: '--font-noto_sans_tc',
  subsets: ['latin'],
});

// ...他のコード

export default function RootLayout({ children }) {
  return (
    <body
      className={`${manropeSans.variable} ${notoSansTC.variable} antialiased bg-white`}
      data-scroll-behavior='smooth'
    >
      {children}
    </body>
  );

Next.js公式説明

Getting Started: Font Optimization | Next.js Learn how to optimize fonts in Next.js nextjs.org