반응형

리액트에서 styled components를 활용하여 전역 공통 css부분을 적용할 수가 있는데요.

이때 폰트를 적용하는 방법을 알아보고자 합니다.

 

프로젝트 로컬에 위치한 폰트 연결하기

먼저 프로젝트 내부에 존재하는 ttf, woff, woff2등의 웹 폰트 파일을 연결하는 방법입니다.

 

1. 폰트 파일 준비

- src/assets/fonts/Pretendard 디렉토리에 원하는 파일들을 위치시켰습니다.

 

이후, 해당 파일을 import하여 전역 스타일링을 할 GlobalStyle에서 사용을 합니다.

 

2. 전역 스타일링 파일 GlobalStyle.ts

import { createGlobalStyle } from "styled-components";
import PretendardExtraLight from "./assets/fonts/Pretendard/PretendardExtraLight.woff2";
import PretendardRegular from "./assets/fonts/Pretendard/PretendardRegular.woff2";
import PretendardBold from "./assets/fonts/Pretendard/PretendardBold.woff2";
import PretendardExtraBold from "./assets/fonts/Pretendard/PretendardExtraBold.woff2";

const GlobalStyle = createGlobalStyle`
    @font-face {
        font-family: 'Pretendard';
        font-weight: 200;
        src: url(${PretendardExtraLight}) format('woff2');    
        unicode-range: U+AC00-D7A3;
    }

    @font-face {
        font-family: 'Pretendard';
        font-weight: 400;
        src: url(${PretendardRegular}) format('woff2');    
        unicode-range: U+AC00-D7A3;
    }

    @font-face {
        font-family: 'Pretendard';
        font-weight: 700;
        src: url(${PretendardBold}) format('woff2');    
        unicode-range: U+AC00-D7A3;
    }

    @font-face {
        font-family: 'Pretendard';
        font-weight: 800;
        src: url(${PretendardExtraBold}) format('woff2');    
        unicode-range: U+AC00-D7A3;
    }
    body {
    	font-family: 'Poppins', 'Pretendard', sans-serif;
    }
`;

export default GlobalStyle;

- src/GlobalStyle.ts

 

import를 통해 폰트 파일 위치의 woff2 파일들을 import하고 @font-face에 적용을 해줍니다.

저는 한글에만 pretendard가 동작하도록 unicode-range를 설정하였습니다.

여기서 그대로 따라하다보면 import부분에서 woff2확장자에 대해 알 수 없기에 오류가 발생할 것입니다.

typescript에게 woff2확장자에 대해 인식할 수 있도록 파일을 추가 생성합니다.

 

3. fonts.d.ts 생성

declare module "*.woff2";
declare module "*.ttf";
declare module "*.woff";

- src/fonts.d.ts

 

ttf, woff도 사용 할 수도 있기에 추가해두었습니다.

저장을 하면 import 오류부분이 사라지는 것을 볼 수 있습니다.

 

4. GlobalStyle.ts 적용하기

최상단 컴포넌트인 index.tsx또는 App.tsx부분에 적용을 해주면 폰트가 바로 적용되는 것을 확인 할 수 있습니다.

import React from "react";
import styled, { ThemeProvider } from "styled-components";
import GlobalStyle from "./GlobalStyle";
function App() {

  return (
    <ThemeProvider theme={"mars"}>
      <GlobalStyle />      
    </ThemeProvider>
  );
}

export default App;

- src/App.tsx

반응형