フォント最適化
next/fontモジュールはフォントを自動的に最適化し、外部ネットワークリクエストを削除することで、プライバシーとパフォーマンスを向上させます。
組み込みのセルフホスティングにより、任意のフォントファイルに対応しています。つまり、レイアウトシフトなしでWebフォントを最適に読み込むことができます。
next/fontの使用を開始するには、next/font/localまたはnext/font/googleからインポートし、適切なオプションを指定して関数として呼び出し、フォントを適用したい要素のclassNameを設定します。以下が例です。
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}フォントは、それが使用されるコンポーネントにスコープされます。アプリケーション全体にフォントを適用するには、ルートレイアウトに追加します。
Google Fonts
Google Fontを自動的にセルフホストできます。フォントは静的アセットとして保存され、デプロイされたドメインと同じドメインから提供されます。つまり、ユーザーがサイトを訪問する際に、ブラウザからGoogleにリクエストが送信されることはありません。
Google Fontの使用を開始するには、next/font/googleから選択したフォントをインポートします。
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}最高のパフォーマンスと柔軟性を得るため、可変フォントの使用を推奨します。ただし、可変フォントが使用できない場合は、ウェイトを指定する必要があります。
import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
)
}ローカルフォント
ローカルフォントを使用するには、next/font/localからフォントをインポートし、ローカルフォントファイルのsrcを指定します。フォントはpublicフォルダに格納したり、appフォルダ内に配置したりできます。以下が例です。
import localFont from 'next/font/local'
const myFont = localFont({
src: './my-font.woff2',
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
</html>
)
}1つのフォントファミリーに複数のファイルを使用したい場合、srcは配列にできます。
const roboto = localFont({
src: [
{
path: './Roboto-Regular.woff2',
weight: '400',
style: 'normal',
},
{
path: './Roboto-Italic.woff2',
weight: '400',
style: 'italic',
},
{
path: './Roboto-Bold.woff2',
weight: '700',
style: 'normal',
},
{
path: './Roboto-BoldItalic.woff2',
weight: '700',
style: 'italic',
},
],
})