Published On

Next.js에서 Font를 설정하는 방법


Google Fonts에서 시작하여, 자체 호스팅 폰트까지, 그리고 이 모든 것을 Next.js의 최적화된 성능과 함께 어떻게 효과적으로 관리할 수 있는지 탐구해 보겠습니다.

구글 폰트 사용 방법@font-faceLocalFont를 사용하는 방법에 대해 소개하겠습니다.

Google Fonts

구글 폰트

@/app/layout.tsxjavascript
import { Inter, Roboto } from "next/font/google";

const roboto = Roboto({ subsets: ["latin"], weight: "500", variable: "--roboto" });
const inter = Inter({subsets:['latin'], weight:['300','500'], variable: "--inter" })

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head />
      <body className={`${roboto.className}`}>
        {children}
      </body>
    </html>
  );
}

폰트 정보 확인

console.log(roboto)
// 결과는 아래처럼 나옵니다.
{
  style: {
    fontFamily: "'__Roboto_54aa2a', '__Roboto_Fallback_54aa2a'",
    fontWeight: 500,
    fontStyle: 'normal'
  },
  className: '__className_54aa2a',
  variable: '__variable_54aa2a'
}

TailwindCSS 설정

  1. 원하는 구글 폰트를 홈페이지에서 찾습니다.
  2. subsets, weight을 설정합니다.
  3. 페이지 전체적으로 사용할지 부분적으로 사용할지 정하고, 부분적으로 필요 시 variable접두어 --를 붙여서 정해줍니다.
  4. Tailwind CSS를 적용 시 tailwind.config.tsvariable을 채워줍니다.
tailwind.config.tsjavascript
module.exports = {
  theme: {
    extend: {
      fontFamily: {
        inter: ['var(--inter)'],
        roboto: ['var(--roboto)'],
      },
    },
  },
  plugins: [],
};
  1. 원하는 태그에 className, variable, style을 넣어줍니다.
layout.tsxjavascript
// body태그 전체에 roboto font 적용
<body className={`${roboto.className}`}>{children}</body>

// body태그 전체에 roboto font 적용
<body style={roboto.style}>{children}</body>


// 태그 별 폰트 적용
// 각각 다른 폰트를 적용
<p className='--roboto'>roboto font</p>
<p className='--inter'>inter font</p>

<p className='font-roboto'>Roboto Font</p>
<p className='font-inter'>Inter Font</p>

외부 폰트 사용 방법

@font-face를 이용하여 폰트 사용

전통적인 css를 이용하는 방법입니다.

파일의 위치는 public에 있어야 합니다.

globals.csscss
@font-face {
  font-family: "PretendardVariable";
  src: url("/fonts/PretendardVariable.ttf");
}

body {
  font-family: -apple-system, PretendardVariable, sans-serif;
}

localFont를 이용하여 폰트 사용

로컬 폰트의 장점은 성능 최적화입니다.

localFont를 사용하면 폰트 파일을 로컬 서버에서 직접 제공하므로, 외부 서버에 대한 의존성이 줄어듭니다.

이는 폰트 로딩 시간을 단축시켜 페이지 로딩 성능을 향상시킵니다.

또한, 로컬 폰트 파일은 브라우저 캐시를 효율적으로 사용할 수 있어, 재방문 시 폰트 로딩 속도가 빨라집니다.

@/app/layout.tsxjavascript
import localFont from 'next/font/local'

const pretendard = localFont({
  src: './fonts/PretendardVariable.ttf'
})
const suit = localFont({ src:'./fonts/SUIT-Variable.ttf'})

<body className={`${pretendard.className}`}>{children}</body>