프레임워크 하나를 배울때마다 에러가 빵빵 터진다.

조용히 넘어가는 날들이 없다.

Next.js에서 styled-components를 적용하려는데 SSR로 인해 style이 들어가기도 전에 렌더링이 되어버린다.

이럴 때는 일단 설치한다.

yarn add babel-plugin-styled-components -D

루트 디렉터리에 .babelrc를 생성한다.

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

3. pages에 _document.js를 생성해서 덮어쓴다.(_document.js가 index.hmtl)

import Document, {
  Html, Head, Main, NextScript,
} from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () => originalRenderPage({
        enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
      });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }

  render() {
    return (
      <Html>
        <Head>
          <style />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

해결이다.

진도 나가고 싶다.

오류 그만 터져라

Leave a comment

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다