Next.js LocalFont 적용하기 (feat. Pretendard)

나주엽·2024년 3월 27일
0
post-thumbnail

next/font

Font Optimization

next/font will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance.

next/font 는 불필요한 외부 네트워크 요청을 없애고, 폰트를 자동적으로 최적화 해줍니다.

next/local/font 를 활용하면 Google Fonts 가 아닌 src 내의 font 파일도 불러와 사용할 수 있습니다.

Preloading

font function 을 호출하는 위치에 따라서, preloading 범위를 지정하게 됩니다.

  • page 내부에서 호출한 경우, 해당 page에서만 preloading 됩니다.
  • layout 에서 호출한 경우, 해당 layout 에 의해 감싸진 모든 페이지에 preloading 됩니다.
  • root layout 에서 호출한 경우, 모든 루트에 대해 preloading 됩니다.

이 글에서는 root layout 에서 호출하겠습니다.

Pretendard 다운받기

Pretendard 는 아래의 링크에서 다운받을 수 있습니다.

Pretendard - 깃허브

다운받은 폰트 중 PretendardVariable.woff2 파일을 src/fonts 에 넣어주겠습니다.

Pretendard 적용하기

localFont

프로젝트 구조는 아래와 같습니다.

src
 ┣ app
 ┃ ┣ favicon.ico
 ┃ ┣ globals.css
 ┃ ┣ layout.tsx
 ┃ ┣ page.tsx
 ┃ ┗ ...
 ┣ features
 ┣ fonts
 ┃ ┗ PretendardVariable.woff2
 ┗ ...

src/app/layout.tsx 에서 localFont 함수를 호출하겠습니다.

// src/app/layout.tsx
import localFont from 'next/font/local'
...

const pretendard = localFont({
  src: '../fonts/PretendardVariable.woff2',
  display: 'swap',
  weight: '45 920',
  variable: '--font-pretendard',
})

export const metadata: Metadata = {
	...
}

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
      <html lang="ko">
        <body className={`${pretendard.variable} font-pretendard`}>
          {children}
        </body>
      </html>
  )
}
  • src : font 함수가 호출된 위치 기준으로 상대경로를 작성해야 합니다.
  • variable : TailwindCSS에서 프리텐다드를 이용하기 위해 작성해줍니다.

TailwindCSS

localFont 에서 설정한 CSS-Variable을 이용해 Tailwind 설정에 추가합니다.

// tailwind.config.ts
import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      fontFamily: {
        pretendard: ['var(--font-pretendard)'],
      },
    },
  },
  plugins: [],
}

export default config

사용하기

"font-pretendard font-black" 등과 같이 사용할 수 있습니다.

적용 후

참고

2개의 댓글

comment-user-thumbnail
2024년 4월 19일

글 잘봤습니다.

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

공식 문서에서는 ${inter.variable}과 같이 className에 variable만 넣어주는데, 'font pretendard'도 같이 넣어줘야 하는 이유를 알 수 있을까요?
링크는 여기 있습니다.
[추가] 혹시 페이지 라우터를 사용하셨나요?
링크에서는 글쓴이분과 같이 사용을 하고 있네요.

1개의 답글