회사에서 프로젝트를 진행하던 중 처음부터 세팅해야 할 일이 생겨 기록하기 위해 이 글을 남긴다 😀
Next.js 공식 문서에서는 localFont 사용이 성능에 좋지 않다고 안내하고 있다. 그러나 기본 CSS @font-face를 사용하면 폰트 로딩 시 깜박임 문제가 발생할 수 있고, 이를 방지하기 위해 localFont를 사용하여 폰트를 적용했다. 다만 구글 폰트를 사용한다면 localFont는 사용할 필요가 없다.
display: swap은 폰트 로딩 중에 텍스트가 기본 폰트로 먼저 렌더링되고, 폰트 파일이 로드되면 해당 폰트로 교체되도록 한다. 자세한 작동 방식은 아래와 같다.
Next와 TailwindCSS가 설치되어있다는 가정하에 진행 할 것이다.
우선 폴더 구조를 살펴보자.
📦src
┗ 📂app
┃ ┣ 📂fonts
┃ ┃ ┣ 📜Pretendard-Black.woff2
┃ ┃ ┣ 📜Pretendard-Bold.woff2
┃ ┃ ┣ 📜Pretendard-ExtraBold.woff2
┃ ┃ ┣ 📜Pretendard-ExtraLight.woff2
┃ ┃ ┣ 📜Pretendard-Light.woff2
┃ ┃ ┣ 📜Pretendard-Medium.woff2
┃ ┃ ┣ 📜Pretendard-Regular.woff2
┃ ┃ ┣ 📜Pretendard-SemiBold.woff2
┃ ┃ ┣ 📜Pretendard-Thin.woff2
┃ ┃ ┗ 📜index.ts
┃ ┣ 📜favicon.ico
┃ ┣ 📜globals.css
┃ ┣ 📜layout.tsx
┃ ┗ 📜page.tsx
폴더 구조는 취향차이 이므로 넘어가고 우선 fonts
폴더 안 index.ts
파일을 살펴보자
// index.ts
import localFont from "next/font/local";
export const pretendard = localFont({
src: [
{
path: "./Pretendard-Thin.woff2",
weight: "100",
},
{
path: "./Pretendard-ExtraLight.woff2",
weight: "200",
},
{
path: "./Pretendard-Light.woff2",
weight: "300",
},
{
path: "./Pretendard-Regular.woff2",
weight: "400",
},
{
path: "./Pretendard-Medium.woff2",
weight: "500",
},
{
path: "./Pretendard-SemiBold.woff2",
weight: "600",
},
{
path: "./Pretendard-Bold.woff2",
weight: "700",
},
{
path: "./Pretendard-ExtraBold.woff2",
weight: "800",
},
{
path: "./Pretendard-Black.woff2",
weight: "900",
},
],
variable: "--font-pretendard",
display: "swap",
});
Pretendard
를 사용할 것이기 때문에 Next
에서 제공하는 localFont
를 사용해준다.
이제 tailwind.config.ts 파일을 바꾸어보자
//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: {
sans: ["var(--font-pretendard)", "sans-serif"],
},
},
},
plugins: [],
};
export default config;
sans
에 pretendard를 적용하는 이유는 sans
가 기본 상속 폰트를 의미하기 때문에 적용시킬 폰트를 가장 앞으로 넣어준다.
// layout.tsx
import type { Metadata } from "next";
import { pretendard } from "./fonts";
import "./globals.css";
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="ko" className={pretendard.variable}>
<body>{children}</body>
</html>
);
}
font-family를 확인해보면 Pretendard가 잘 적용된 것을 확인 할 수 있다!