0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js/TailwindCSS】フォントを最適化してみよう | Next.js Tutorial #3 - Optimizing Fonts and Images

Posted at

なぜフォントを最適化する必要があるのか

  • フォントは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クラスは必須のクラスではないが、フォントの境目をスムーズにすることができる。

Intersubsetsに指定できるのは以下のものだけ
・"cyrillic"
・"cyrillic-ext"
・"greek"
・"greek-ext"
・"latin"
・"latin-ext"
・"vietnamese"

  • Intersubsetsにそれ以外のものを指定すると下記のエラーが発生します。

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"
 });

補足

  • InterclassNameがよく分からなかったので、定義を参照する
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;
};

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?