なぜフォントを最適化する必要があるのか
- フォントはWebサイトの中で重要な役割を果たしますが、フォントファイルを読み込む場合はパフォーマンスにパフォーマンスに重要な影響を与えることがあります。
Fonts play a significant role in the design of a website, but using custom fonts in your project can affect performance if the font files need to be fetched and loaded.
- Next.jsは
next/fontモジュールを使う際に自動的にアプリケーションのフォントを最適化します。また、ビルドしてホストする際にフォントファイル及び他のStaticな(静的な)アセットをダウンロードすることが出来ます。ユーザーの訪問時に、Webサイトのパフォーマンスに影響を与えるような、追加のネットワーク上のリクエストをしないということを意味しています。
プライマリフォントを追加してみる
-
/app/uiディレクトリにfonts.tsというファイルを作成する。 -
next/font/googleというモジュールの中にあるInterというライブラリを使用して、その中で'latin'というサブセットを詳述する。 -
Interを用いることで、フォント全体に共通フォントが適用される。 -
antialaisedクラスは必須のクラスではないが、フォントの境目をスムーズにすることができる。
Interのsubsetsに指定できるのは以下のものだけ
・"cyrillic"
・"cyrillic-ext"
・"greek"
・"greek-ext"
・"latin"
・"latin-ext"
・"vietnamese"
-
Interのsubsetsにそれ以外のものを指定すると下記のエラーが発生します。
Type '"japanese"' is not assignable to type '"cyrillic" | "cyrillic-ext" | "greek" | "greek-ext" | "latin" | "latin-ext" | "vietnamese"
/// fonts.ts
+ import { Inter } from 'next/font/google';
+ export const inter = Inter({ subsets: ['latin'] });
/// layout.tsx
import '@/app/ui/global.css';
+ import { inter } from '@/app/ui/fonts';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
+ <body className={`${inter.className} antialiased`}>{children}</body>
</html>
);
}
実際にサンプルコードを書いてみよう
/// fonts.ts
// 新しいフォントを適用するには、
// InterをLustianaに変更すればよい
// あとフォントによって指定できるプロパティに限りがある
export const inter = Inter({ subsets: ['latin'] });
export const lustiana = Lusitana({
weight: "400"
});
補足
-
InterのclassNameがよく分からなかったので、定義を参照する
export type CssVariable = `--${string}`;
export type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional';
export type NextFont = {
className: string; // ここ
style: {
fontFamily: string;
fontWeight?: number;
fontStyle?: string;
};
};
export type NextFontWithVariable = NextFont & {
variable: string;
};
参考