TIL.51 Styled Component 에서 web font 사용하기

Haiin·2021년 2월 6일
6
post-thumbnail

출저



1. font 다운받기

I'd advise you to import at least those two font formats, woff and woff2, since they have been recommended by the W3C and are widely supported on all browsers.

W3C에서 추천하는 모든 브라우저에서 이용 가능한 woff, woff2 format을 가진 폰트를 다운로드 받는다.

WOFF ?

Web Open Font Format

OTF와 TTF의 무단배포 등의 문제 등을 해결하기 위해 모질라 재단과 오페라 소프트웨어, 마이크로소프트에서 제안한 웹폰트 파일 형식이다.
기본적으로 OTF, TTF를 이용한 구조를 하고 있으며, 압축된 버전이라 웹에서 다운받아가며 사용하기에 최적화되어있다. 또한 글꼴 파일내에서 라이센스 및 메타데이터 등을 따로 포함할 수 있어 저작권 문제에 도움을 준다.
이후, WOFF2 라는 파일 형식이 추가로 개발되었는데, 기존 WOFF에 비해 30% ~ 50% 정도 더 압축되어 훨씬 가볍다. 2018년 기준으로는 IE를 제외한 거의 모든 브라우저의 최신 버전에서 지원하고 있다.



2. fonts 폴더 구조

In your React project, create a folder in your src folder and name it 'fonts'. In this folder create a file which you call fonts.js - this will contain the imports for your fonts and will later make them available to the rest of your app.

2-1. src 폴더안에 `fonts`라는 폴더를 만든다.
2-2. 이 안에 다운받은 woff 포멧의 폰트파일을 넣고, 
2-3. `fonts.js`라는 파일을 만든다. 이 안에 다운받은 폰트를 import하여 프로젝트 안에서 사용할 수 있게 만들어 줄 것 이다.



3. fonts.js 작성

In your fonts.js file import the { createGlobalStyle } from 'styled-components'. This is a handy little helper that handles global css styles in your app.

3-1. styeld-components에서 createGlobalStyled을 import 한다.(앱에서 전역 CSS 스타일 처리)
3-2. 다운로드한 woff 폰트 파일을 import 한다.
3-3. font-face 를 작성한다.
src/styles/fonts/fonts.js

import { createGlobalStyle } from "styled-components";
import MontHeavyDemo from "./Mont-HeavyDEMO.woff";

export default createGlobalStyle`
    @font-face {
        font-family: "Mont Heavy Demo";
        src: local("Mont Heavy Demo"),
        url(${MontHeavyDemo}) format('woff');
        font-weight: 300;
        font-style: normal;
    }
`;


4. 컴포넌트에 적용하고 사용하기

Somewhere in the App.js file, preferably just below a normal styled component that would typically contain site layout or similar and doesn't need any font styles, place the GlobalFonts component in your return of the render

4-1. fonts.js 파일에서 GlobalFonts 로 import 한다.
4-2. render 안에 배치해 준다.
아래와 같은 경우에는 GlobalStyle을 배치해준 index.js 에 같이 import 하여 전역에서 사용 가능하도록 했다.
4-3. styled-component 에서 사용.
import React from "react";
import ReactDOM from "react-dom";
import GlobalStyle from "./Styles/globalStyles";
import GlobalFonts from "./Styles/fonts/fonts"; //4-1


ReactDOM.render(
  <React.StrictMode>
      <GlobalStyle />
      <GlobalFonts />//4-2
      	<Routes />
  	...
  </React.StrictMode>,
  document.getElementById("root"),
);


const QuestionTitle = styled.div`
    font-family: "MontHeavyDemo";//4-3
`;

1개의 댓글

comment-user-thumbnail
2022년 9월 30일

아니 제목은 web font인데 내용은 폰트를 다운받아서 쓰는 방식이네요?

답글 달기