Programming/Client

[Next.js] Tailwind-styled-components의 SSR 구현하기

Jiwoo 2023. 4. 6. 12:17

🤔 문제 상황

tailwind-styled-components를 사용해서 스타일을 부여했는데
초기 렌더링되는 찰나에 css가 적용되지 않는 문제가 있었다.
자바스크립트 파일이 다운로드 되고 나서야 제대로 적용되니 보기 싫었다.
css가 next.js가 ssr할 때 부여되도록 설정이 따로 필요했다.

Next.js + tailwind + styled-components를 결합할 때
twin.marco + emotion 조합을 더 많이 사용해서 자료가 많았는데,
Next.js와 tailwind-styled-components를 사용하는 경우는 많지 않아서
자료 찾기가 어려웠다. 그래도 좋은 글들이 몇 개 있어서 참고해서 해결했다.

✅ 해결 방법

ssr 적용하지 않는다면 styled-components를 깔지 않고
Tailwind-styled-components만 사용해도 괜찮지만
적용한다면 styled-components도 깔아야한다.
Tailwind-styled-components는 따로 설정할 것이 없다.


1. 필요한 패키지 설치

  • styled-components
  • tailwindcss & tailwindcss-cli & raw-loader
$npm i styled-components @types/styled-components
$npm i tailwindcss tailwindcss-cli raw-loader

2. package.json script 옵션 추가

tailwind를 빌드시에 넣어야 하니까 script안에 해당 코드를 넣어줌

"scripts": {
    "prebuild": "tailwindcss-cli build -o styles/tailwindSSR.css"
},

3. _document 수정

이 파일 안에서 구성이 좀 복잡해진다.
단순하게 얘기하면 styled-components에서 ServerStyleSheet라는 기능을 가져와서
head 태그 안에 styled-components를 style태그로 넣어줌
그리고 tailwindSSR에서 bundleCSS를 가져와서 tailwind를 css로 빌드해서 넣는 것이다.
주의할 점은 //@ts-ignore 주석을 생략하지 말 것! (에러 발생함)

import Document, {
  DocumentContext,
  Html,
  Head,
  Main,
  NextScript,
} from "next/document";
import { ServerStyleSheet } from "styled-components"; // head 태그 안에 styled-components를 style태그로 넣어줌
// @ts-ignore
import bundleCss from "!raw-loader!../assets/styles/tailwindSSR.css"; // 위에 @ts-ignore 생략시 오류 발생

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    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 lang="en">
        <Head>
          <meta property="og:title" content="Next.js로 만든 사이트" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

4. tailwind-styled-components 설치

$ npm i tailwind-styled-components

이제 tailwind-styled-components를 설치하고 사용하면 된다.
이렇게 하면 javascript 옵션을 꺼도 css가 적용된 화면을 볼 수 있다.
javascript 옵션 끄기는 크롬 확장 프로그램 quick javascript switch 사용하면 된다.



참고
engschool.tistory