LoginSignup
0
0

Next.jsでフォントを設定する

Last updated at Posted at 2024-04-20

初めに

Next.jsの最新バージョンでのフォントの設定についてです。説明しているサイトが少なかったので忘備録として残します。

注意事項

プログラミング初心者の記事になります。明らかな誤りがある際にはコメントいただけると幸いです。

結論

まずは簡単に設定手順を記します。

  1. font.tsを作成する
  2. next/font/googleから使用するファントの種類をインポート
  3. 任意のファイルで呼び出す

以下詳しい設定方法です。

font.tsの作成

まずは好きな場所にfont.tsを作成してください。
今回はappディレクトリ配下にそのまま設置しましたが、uiファイルを作成してもいいかもです。

スクリーンショット 2024-04-20 14.46.23.png

next/font/googleから使用するファントの種類をインポート

使用するフォントを読み込んでください。今回はお試し用なのでInter, Lusitana, Montserrat, Noto_Sans_JPといろいろ読み込んでみました。

読み込んだフォントは変数にして、読み込む内容を設定してあげてください。Variable fonts でない場合は weight の指定が必須です。

// src/app/fonts.ts

import { Inter, Lusitana, Montserrat, Noto_Sans_JP } from 'next/font/google';

export const inter = Inter({ subsets: ['latin'] });

export const lusitana = Lusitana({
  weight: ['400', '700'],
  subsets: ['latin'],
});

export const montserrat = Montserrat({
  weight: ['400', '500', '700'],
  subsets: ['latin'],
});

export const notoSansJP = Noto_Sans_JP({
  subsets: ['latin'],
  variable: '--font-noto-sans-jp',
});

任意のファイルで呼び出す

import { notoSansJP } from '@/app/fonts';で必要なフォントを呼び出して、className=${notoSansJP.className}で設定したい要素に記載しています。今回はbodyタグで画面全体に使用していますが、細かいフォント設定も可能です。

import { notoSansJP } from '@/app/fonts';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="ja">
      <body className={`${notoSansJP.className} flex flex-col min-h-screen`}>
        {children}
      </body>
    </html>
  );
}

最後に

この記事は以下のサイトを参考にしています。

0
0
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
0
0