[Next] CNA (Next, TypeScript, Styled-components) 세팅 후 SSR시 css 적용 안되는 현상

손종일·2020년 12월 15일
1

Next.js

목록 보기
3/5
post-thumbnail

이전에 블로그에 올렸던 CNA (TypeScript, Next, Styled-components) 세팅 방법을 다루었었다.

하지만 tyled-components를 적용하면 되는데 SSR했을 경우에 처음에 적용이 되지 않았다. 이 이슈에 대한 해결 내용을 다루도록 하겠습니다.

(스타일이 적용되기 전에 이미 Server-Side-Rendering 되어 적용되지 않음)

1. .babelrc 설정

아래처럼

----------------------------------------------------------------------.babelrc
{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    [
      "styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ]
  ]
}

2. _document.tsx 설정

Next js에서 제공되는 코드도 있지만 깜빡거리는 현상이 있을 수 있습니다.
깜빡인다면 하기의 코드를 사용하시면 됩니다.
하기의 코드는 참고 링크 첨부합니다.

----------------------------------------------------------------------_document.tsx

import Document, { Head, Main, NextScript } from 'next/document';
import React from 'react';
import { ServerStyleSheet } from '../styles/themed-components';

interface StyledProps {
  styleTags: Array<React.ReactElement<{}>>;
}

export default class MyDocument extends Document<StyledProps> {
  // getInitialProps로 스타일에 대한 정보를 모아서 적용시킨 다음 렌더링 시키기 위하여
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();
    const page = renderPage((App) => (props) =>
      sheet.collectStyles(<App {...props} />),
    );

    const styleTags = sheet.getStyleElement();
    return { ...page, styleTags };
  }

  render() {
    return (
      <html>
        <Head>
          <title>Sohn Next</title>
          {this.props.styleTags}
        </Head>
        <body>
          <Main/>
          <NextScript />
        </body>
      </html>
    );
  }
}

위 처럼 .babelrc와 _document.tsx를 설정한다면 SSR되기 전에 스타일을 적용 시킨 후 렌더링 할 수 있습니다.

profile
Allday

0개의 댓글