Next.js에서 구글 폰트를 간편하게 적용하려면 @next/font 패키지를 사용하는 방법이 있다.
이 글에서는 @next/font 패키지를 설치하고, 구글 폰트를 프로젝트에 적용하는 방법을 단계별로 알아보자.
1. @next/font 패키지 설치하기
먼저, 프로젝트에 @next/font 패키지를 설치해야 한다.
npm install @next/font
2. 구글 폰트 가져오기
구글 폰트를 가져오는 방법을 살펴보자. 예를 들어 Noto Sans 폰트를 사용해보겠다.
2.1. 폰트 설정하기
Next.js에서는 @next/font 패키지를 사용해 구글 폰트를 쉽게 설정할 수 있다. pages/_app.tsx 또는 pages/_document.tsx 파일에서 다음과 같이 폰트를 가져오고 적용할 수 있다.
pages/_app.tsx 예시
import '@/styles/globals.css';
import type { AppProps } from 'next/app';
import { Noto_Sans } from 'next/font/google';
const notoSans = Noto_Sans({ subsets: ['latin'], weight: ['400', '700'] });
function MyApp({ Component, pageProps }: AppProps) {
return (
<div className={notoSans.className}>
<Component {...pageProps} />
</div>
);
}
export default MyApp;
pages/_document.tsx 예시
또는 pages/_document.tsx에서 폰트를 설정할 수도 있다.
import { Html, Head, Main, NextScript } from 'next/document';
import { Noto_Sans } from 'next/font/google';
const notoSans = Noto_Sans({ subsets: ['latin'], weight: ['400', '700'] });
export default function Document() {
return (
<Html lang="en">
<Head>
<style>{`
body {
font-family: ${notoSans.style.fontFamily};
}
`}</style>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
3. 글로벌 CSS 파일 수정하기
폰트를 설정한 후, 글로벌 CSS 파일에서 기본 폰트를 Noto Sans로 설정할 수도 있다.
styles/globals.css 파일을 열고 다음과 같이 설정하자.
body {
font-family: 'Noto Sans', sans-serif;
}
4. 결과 확인하기
모든 설정을 마친 후, 프로젝트를 실행하고 브라우저에서 폰트가 제대로 적용되었는지 확인해본다.