React에서 font 적용하기 (with TypeScript) - boostcampwm-2021/WEB25-JustUs GitHub Wiki

스크린샷 2021-11-11 오전 12.39.07.png

사용하고자 하는 font를 프로젝트 내부에 저장한다.

import { createGlobalStyle } from "styled-components";
import NanumDaCaeSaRang from "../fonts/NanumDaCaeSaRang.ttf";

const GlobalStyle = createGlobalStyle`
  @import url('https://fonts.googleapis.com/css2?family=Nanum+Gothic:wght@400;700;800&display=swap');
  @font-face {
    font-family: "NanumDaCaeSaRang";
    font-weight: 50;
    src: url(${NanumDaCaeSaRang}) format("truetype");
  }
  ...
`;

이후 전역에서 사용되는 styled-component인 GlobalStyleCSS at-rules 중 하나인 @font-face을 설정해준다. font-familysrc는 필수 값이다. src의 뒤에 붙은 format은 앞에 불러온 폰트의 형식을 지정해준다. truetype은 ttf 타입으로, ttf는 True Type Font의 약자다.

스크린샷 2021-11-11 오전 12.46.09.png

@font-face 작성이 끝나면 위와 같은 에러를 마주할 수 있다. ts가 .ttf 포맷을 인식하지 못하기 때문에 발생하는 에러다. 구글링 한 결과 아래와 같은 추가 작업을 통해 에러를 해결할 수 있었다.

  1. 프로젝트의 루트 디렉토리에 fonts.d.ts 파일을 생성한 뒤 아래와 같이 작성한다.

    // fonts.d.ts
    
    declare module "*.ttf";
    
  2. tsconfig.jsoninclude에 방금 만든 파일을 추가해준다.

    {
      ...
    	"include": [
        ...
        "fonts.d.ts"
      ],
      ...
    }
    
  3. vs code를 리부팅하면 해당 에러가 사라진다.

// PostInfoModal.tsx

const PostTitle = styled.div`
  ${flexRowCenterAlign}
  grid-column-start: 2;
  grid-column-end: 3;
  font-size: 2rem;
  font-family: "NanumDaCaeSaRang";
`;

위의 설정들을 모두 마치고 나면, GlobalStyle이 프로젝트 전역에 적용되기에, 원하는 곳에서 해당 폰트를 사용할 수 있게 된다.