본문 바로가기
Next JS

Next JS 버전 14 로컬 폰트 적용하기

by 왜안돼요 2024. 5. 7.

 

--------------

 

하 진짜... 이름값 한다... 왜 안돼요./...

 

이번에 프로젝트 시작하면서 nextJs 를 사용해보려고 야심차게 깔고

어려워서 계속 헤맨다.

그냥 react 같았으면 폰트적용 뚝딱 했을텐데 이번엔 tailwindcss랑 같이 쓰다보니

더 헷갈려서 나중에 또 써먹을일 있을까봐 기록용으로 써둠.

 

 

일단 폰트들은 public/fonts에 담아둿음

 

뭐 블로그 찾아보니까 app 폴더에 fonts 폴더 넣어도 된다고는 하는디..그냥 찝찝해서 나는 퍼블릭에 넣엇음

 

app 안에있는 글로벌.css에 백날천날 폰트페이스, 폰트패밀리 적용해도 소용 1도 없다.... 우선순위 다 밀림.. 내가 봄.

 

next/font

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

next/font/local을 활용하면 googlefonts가 아닌 src 내의 font 파일도 불러와 사용할 수 있따!

 

폰트 다운

pretendard 같은 경우에는 공홈에서 다운받을 수 있음

깃허브 가면 아예 라이브러리로 지원도 해줌.

폰트 파일형식이 여러개인데 그중에

PretendardVariable.woff2 파일을 사용하면 된다

 

Preloading

font function을 호출하는 위치에 따라, Preloading 범위를 지정할수 있다.

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

나는 전역적으로 pretendard 가 적용되면 좋겟어서 rootlayout에 호출해줬다.

import localFont from 'next/font/local';

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

const didot = localFont({
  src: "../public/fonts/Didot.otf",
  display: "swap",
  variable: "--font-didot"

})


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="en" className={didot.variable}>
      <body className={pretendard.className}>
        <MSWComponent>
          <Header />
          {children}
        </MSWComponent>
      </body>
    </html>
  );
}

 

 

 

공식문서에 친절히 나와있지만. 나는 영어 못함이슈로 .... 얼마없는 14버전 폰트적용 블로그.. 싺싹 핥음

 

 

Optimizing: Fonts | Next.js

Optimize your application's web fonts with the built-in `next/font` loaders.

nextjs.org

 

 

localFont 임포트 해주시고요

 

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

const didot = localFont({
  src: "../public/fonts/Didot.otf",
  display: "swap",
  variable: "--font-didot"

})

 

이런식으로 작성해주면되는데

나는 경로때문에 꽤나 .. 삽질함

아니 퍼블릭이면 당연히 /fonts/어쩌구 아니냐고..

심지어 기본설정 @ 이걸로 적용해놔서

@/fonts -> x

기타 등등

할수있는거 다해봄 

하지만 안됐음

결국 ../public 이엿음..

허허,,, 왜 적용이 안되는거죠

 

아무튼 이런식으로 설정해뒀으면

 

리턴 부분에도 만들어둔 상수 선언을 해줘야한다

 

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en" className={didot.variable}>
      <body className={pretendard.className}>
        <MSWComponent>
          <Header />
          {children}
        </MSWComponent>
      </body>
    </html>
  );
}

didot 폰트는 포인트로 줄거라 variable로 줬고 pretendard는 전역으로 쓸거라 className으로 해줬음 근데 그냥 html 태그안에서 다 설정해줘도 될것같다.

나 왜저렇게 해놨지 싶지만 이미. 디벨롭에 머지해서 돌릴수없다.

 

++ 사실 여기까지만 해도 무관하다! 나는 여기까지 했음에도 적용이 안됐던걸로 기억함 그래서 그냥 테일윈드로 지정함

 

TailwindCSS 적용

이제ㅔ 저렇게 해줬으면 테일윈드에서 사용할수있게 설정을 해줘야한다.

tailwindCss.config.ts 파일에가서

import type { Config } from "tailwindcss";

const config: Config = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      colors: {
        mainBlack: "#131213",
        mainWhite: "#FDFCF7",
        footerOrange:"#FF5634"
      },
      fontFamily:{
        didot: ["var(--font-didot)"],
        pretendard : ["var(--font-pretendard)"]
      }
    },
  },
  plugins: [require('@tailwindcss/forms')],
};
export default config;

이런식으로 설정해주면 끝~

 

+ 추가

테일윈드가 버전이 업데이트 되면서 tailwind.config.js가 없어졌다.

@import 'tailwindcss';

@font-face {
  font-family: 'Pretendard Variable';
  font-weight: 45 920;
  font-style: normal;
  font-display: swap;
  src: url('/fonts/PretendardVariable.woff2') format('woff2-variations');
}

@theme {
  --font-pretendard: 'Pretendard Variable';
}

그냥 index.css에 theme으로 지정해주어야한다!

사용

이런식으로 선언해서 사용해주면 된다. 

 

참고블로그

 

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

Next.js 프로젝트에 next/font/local 을 이용하여 폰트 적용하기, (feat. Pretendard)

velog.io

 

 

🧱Next.js 14에 Pretendard 폰트 적용하기

이번 글에서는 Next.js 14 버전에서 Pretendard 폰트를 적용하는 법과, 기존에 cdn에서 폰트를 적용하는 것에 비해서 어떤 최적화가 이루어지는지 다루겠습니다. 현재...

dev.to

 

 

나노 학습 : Next 14에서 Font 적용하기 (프리텐다드 로컬 폰트)

Next 14에서 Font 적용하기 pretendard : GitHub orioncactus/pretendard: 어느 플랫폼에서든 사용할 수 있는 system-ui 대체 글꼴 A system-ui alternative font for all cross-platform - 가장 예쁨

tilnote.io

 

'Next JS' 카테고리의 다른 글

next js 14 + tailwindCSS폰트적용하기 2  (1) 2024.11.04
Next Js에서 msw 사용하기  (1) 2024.05.07
1일차 Next js  (0) 2024.02.27

최근댓글

최근글

skin by © 2024 ttuttak