🎉

Next.js Font Optimization

2022/05/13に公開

Next.js の Font Optimization を導入したので備忘録

実施環境
項目 詳細
PC MacBook Pro(14インチ、2021)Apple M1 Pro
OS MacOS Monterey 12.3
Node.js v16.14.2
Next.js v12.1.4

概要

By default, Next.js will automatically inline font CSS at build time, eliminating an extra round trip to fetch font declarations. This results in improvements to First Contentful Paint (FCP) and Largest Contentful Paint (LCP).

Next.js v10.2から自動でWebフォントの最適化が行われるようになりました。
たぶんビルド時にフォントを予め取ってきてくれるということ…?

supports Google Fonts and Typekit with support for other font providers coming soon.

Google fontsとTypekitがサポートされているとのこと。

使い方 (Google Fonts)

1. Google Fontsで入れたいフォントを選ぶ

select style を押して、必要なフォントを追加していく。
一般的には、Regular 400の普通、Bold 700の太字の2つで良いはず。

出てくる selected family の中の、<link> 内、最後のlinkをコピー

※ちょっとここ確証ないのですが、下記2つはおそらく不要です。(違うよっていう方いればぜひ教えてください)推察でしかないのですが、preconnect部分はこういう動きをしているっぽく、ビルド時にフォントを読み込むFont Optimizationでは不要だと思われます。公式Tutorialのソースにもなさそうでした。
入れておく場合はcrossoriginがエラーになるので、crossOrigin="trueにします。

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

2. pages/_document.js or ts にGoogle fontsのリンクを貼る

// pages/_document.js

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <link
            href="https://fonts.googleapis.com/css2?family=Inter&display=optional"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

Note that we don't recommend adding fonts with next/head, as this only applies the font to the particular page and won't work with a streaming architecture.

next/head に追加は非推奨とのこと。

3. body等にFont-familyを設定

フォントを当てたい箇所に設定。何を書けばいいかはGoogle fontsに記載あり。

全体で当てたいのであれば、

/styles/globals.css

body {
  ...
  font-family: 'Noto Sans JP', sans-serif;
}

/pages/_app.tsxでスタイルを読み込む。

/pages/_app.tsx

import '@/styles/globals.css';
import type { AppProps } from 'next/app';

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default MyApp;

Font Optimization を消したい場合

// next.config.js

module.exports = {
  optimizeFonts: false,
}

参考リンク

Discussion