Published on

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

Authors
  • avatar
    Name
    Inhwan Cho
    Twitter

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

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

Google Fonts

구글 폰트

layout.tsx
import { Inter, Roboto, Metamorphous } from "next/font/google";

const roboto = Roboto({ subsets: ["latin"], weight: "500", variable: "--roboto" });
const inter = Inter({subsets:['latin'], weight:['300','500'], variable: "--inter" })
console.log(roboto)
// 결과는 아래처럼 나옵니다.
{
  style: {
    fontFamily: "'__Roboto_54aa2a', '__Roboto_Fallback_54aa2a'",
    fontWeight: 500,
    fontStyle: 'normal'
  },
  className: '__className_54aa2a',
  variable: '__variable_54aa2a'
}
  1. 일단 원하는 구글 폰트를 홈페이지에서 찾습니다.
  2. subsets, weight을 설정합니다.
  3. 페이지 전체적으로 사용할지 부분적으로 사용할지 정하고 부분적으로 필요 시 variable을 접두어 --를 붙여서 정해줍니다.
  4. tailwindcss를 적용 시 tailwind.config.tsvariable을 채워줍니다.
tailwind.config.ts
const config={
  ...
  theme: {
    extend: {
      fontFamily: {
        inter : ['var(--inter)'],
        roboto: ['var(--roboto)'],
        ...
      }}}}
  1. 원하는 태그에 className, variable, style을 넣어줍니다.
layout.tsx
// 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>

외부 폰트 사용 방법

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

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

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

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

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

localFont를 이용하여 폰트 사용

layout.tsx
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>