LoginSignup
18
9

More than 1 year has passed since last update.

Next.js で Google Fonts を取り扱うメモ

Posted at

タイトルの通り、Next.js で Google Fonts を使用する方法についての備忘録をまとめます。

Google Fonts

使用したフォントは Noto Sans Japanese です。

日本語対応フォントで細字から太字まで対応している見やすいフリーフォントが欲しかったので、こちらにたどり着きました。

手順

Google Fonts
にアクセスして画像のようにいい感じに絞り込みをしつつ検索します。

フォントの太さをそれぞれリストに追加していきますと、ページ右の欄にあるラジオボタン(<link>@import )で<link>を選択します。

Screen Shot 2021-10-27 at 19.41.44.png

タグが表示されているので、選択部分をコピーしておきます。

Screen Shot 2021-10-27 at 19.58.05.png

Next.js

つづいて Next.js の設定です

Vercel - Font Optimization

まずプロジェクトの page ディレクトリ配下に_document.js を作成します。(拡張子は別に TS でも TSX でも可能です)

/pages/_document.js
import Document, { Head, Html, Main, NextScript } from "next/document";

// class Document extends NextDocument {
class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <link
            href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100;300;400;500;600;700&display=swap"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
export default MyDocument;

next.config.jsでオプションを有効化する

next.config.js
module.exports = {
  experimental: {
    optimizeFonts: true,
  },
};

以上です。
取り込むHeadは_app.tsxに直接記載する方法もあるようですね。難しそうに思いましたが意外と簡単に設定できました。

参考文献など

Google Fonts

using google fonts in nextjs with sass, css and semantic ui react

18
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
9