ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Gatsby.js] Gatsby+Typescript에서 styled-component 본격 설정하기
    development/React 2022. 9. 30. 02:00

    안녕하세요.

    최근 Gatsby로 자기소개 페이지를 간단하게 기획해서 배포까지 완료했었는데요.

    이번에 Gatsby로 제작한 웹 사이트 일부입니다.

    Gatsby + Typescript 스펙을 주로, 스타일 라이브러리로는 styled-components를 사용했습니다.

     

    그런데 이게 Gatsby에선 기본 React프로젝트와는 설정 방식에 살짝 차이가 있어서 이곳저곳 찾아보면서 진행했었는데요.

    아마도 써놓지 않으면 잊을 수 있기 때문에! 간단하게 기록해두겠습니다. 추가적으로 누군가에게 도움도 됐으면 좋겠습니다. 

    1. 패키지 설치

    일단 기본적으로 Gatsby 프로젝트 자체가 생성되어 있다는 전제로 진행합니다. (+ npm 사용)

    styled-components와 관련된 패키지부터 설치해주도록 합니다.

    npm install styled-components @types/styled-components gatsby-plugin-styled-components babel-plugin-styled-components
    • styled-components
      • 기본적으로 styled-components를 사용하기 위해 설치해줍니다.
    • @types/styled-components
      • styled-components의 type definitions을 설치해줍니다.
    • gatsby-plugin-styled-components 
      • Gatsby 환경에서 styled-components를 사용하기 위해 설치해줍니다.
    • babel-plugin-styled-components
      • styled-components는 기본적으로 classname이 hash 값으로 생성되게 됩니다. 이러한 부분은 장점이기도 하지만, 디버깅이 어렵다는 단점도 있습니다.  
      • 이러한 디버깅을 용이하게 하기 위해 component name을 hash 앞에 prefix하여 classname의 가독성을 높이는 라이브러리입니다.

    2. Plugin을 config에 선언하기

    플러그인을 설치만 한다고 해서 사용할 수 있는것은 아닙니다.

    그렇기에 Gatsby의 환경 설정 파일에 1번에서 설치 받은 플러그인을 활성화하는 설정을 작성해줍니다.

     

    프로젝트 최상단 경로에 gatsby-config.ts 파일을 생성해줍니다.

    // gatsby-config.ts
    import type { GatsbyConfig } from 'gatsby';
    
     const config: GatsbyConfig = {
       plugins: [
         `gatsby-plugin-styled-components`
       ],
     };
    
     export default config;

    3. GlobalStyle 설정하기

    styled-components의 Global style을 설정 해주겠습니다.

    Styled-components 방식의 global style을 제작하는 것은 쉽습니다. 공식 문서가 알려주는대로 진행하면 됩니다.

    저는 css-normalize 라이브러리를 사용해 다음처럼 설정 했습니다.

    // GlobalStyle.tsx
    import { createGlobalStyle } from 'styled-components';
    import { normalize } from 'styled-normalize';
    
     export const GlobalStyle = createGlobalStyle`
       ${normalize}
       
       body {
             font-size: 16px;
             font-family: 'SDGothic', sans-serif;
             line-height: 1.5;
             font-weight: normal;
             width: 100%;
             height: 100vh;
             background-color: ${(props) => props.theme.color.background}
         }
         html, body, #root {
             width: 100%;
             height: 100%;
             overflow-x: hidden;
         }
     `;

    그리고 이제 Gatsby 환경에 맞게 설정해주어야 합니다.

    우선적으로 Gatsby 환경에선 전체 페이지를 주관하는 index 파일이 기본적으로 없습니다.

     

    그래서 gatsby-ssr.tsx 파일과 gatsby-browser.tsx 파일을 추가해 각 환경(CSR/SSR)에서 사용할 공통 레이아웃을 정의하는 방식으로 설정을 진행해야 합니다.

     

    그렇기에 우선 공통 레이아웃 파일을 제작해줍니다. 굳이 외부 파일로 분리하지 않아도 되지만, 저는 이렇게 하는 것이 더 편할것 같아 분리했습니다.

    import React from 'react';
    
     import { GlobalStyle } from 'styles/GlobalStyle';
    
     interface Props {
       children: React.ReactNode;
     }
    
     const Layout = ({ children }: Props) => {
       return (
         <>
           <GlobalStyle />
           {children}
         </>
       );
     };
    
     export default Layout;

     

    다음으로 프로젝트 최상단 경로에 gatsby-ssr.tsx 파일을 생성해주고, 다음처럼 설정합니다.

    import type { GatsbySSR } from 'gatsby';
    import * as React from 'react';
    
    import Layout from './src/components/Layout';
    
     export const wrapPageElement: GatsbySSR['wrapPageElement'] = ({ element }) => {
       return <Layout>{element}</Layout>;
     };

    SSR 환경에서의 공통 레이아웃을 설정해주었습니다.

    그럼 당연히 CSR 환경에서도 진행 해주어야겠습니다.

     

    프로젝트 최상단에 gatsby-browser.tsx 파일을 생성해주고, 다음처럼 설정합니다.

    import type { GatsbyBrowser } from 'gatsby';
    import * as React from 'react';
    
    import Layout from './src/components/Layout';
    
    export const wrapPageElement: GatsbyBrowser['wrapPageElement'] = ({ element }) => {
       return <Layout>{element}</Layout>;
    };

    이제 우리는 글로벌 스타일 설정을 완료했습니다.

    4. Theme 설정하기

    테마 기능도 설정해주겠습니다.

    Theme를 우선 작성해주었습니다. 초기 세팅이라 별 내용은 없습니다.

    const Color = {
       background: '#16213E',
     };
    
     const theme = Object.freeze({
       color: Color,
     });
    
     export type Theme = typeof theme;
    
     export default theme;

    styled-component의 theme에 접근할 때 type을 지원해주기 위해 type 선언을 추가해줍니다.

     

    이번 파일은 프로젝트 아무곳에나 작성해도 상관 없습니다. 저는 theme가 위치하는 폴더와 동일한 곳에 넣어주었습니다.

    파일 이름은 styled.d.ts 로 제작합니다.

    import 'styled-components';
    
     import { Theme } from './theme';
    
     declare module 'styled-components' {
       export interface DefaultTheme extends Theme {}
     }

    이렇게 작성하고 난 이후, Theme provider에 테마를 주입시켜주면 끝입니다.

    앞서 작성해주었던 Layout 파일에 내용을 추가해줍니다.

     

    import React from 'react';
    import { ThemeProvider } from 'styled-components';
    
    import { GlobalStyle } from 'styles/GlobalStyle';
    import theme from 'styles/theme';
    
    
    interface Props {
    children: React.ReactNode;
    }
    
    const Layout = ({ children }: Props) => {
        return (
         <ThemeProvider theme={theme}>
           <GlobalStyle />
           {children}
         </ThemeProvider>
        );
    };
    
    export default Layout;

    이로써 Gatsby에서 styled-components 사용 설정을 완료했습니다! 고생하셨습니다.

     


    피드백은 언제나 환영이니 부탁드립니다.

    감사합니다.

Designed by Tistory.