Next.js 를 모바일 웹용으로 사용하던 중 이미지와 css 를 늦게 불러오는 이슈를 발견했다.

아마도 SSR 에서 Document를 불러올 때 HTML을 우선 불러오고 나중에 css 를 불러오는 듯하다.

 

 

CSS가 늦게 불러와져서 화면이 깨진다.

구글링을 해보니 몇 가지 옵션을 추가하면 된다고 한다.

1.Next.config.js 옵션 추가

 
 compiler : {
    styledComponents : true,
  },

 

2._document.tsx 추가 (_app.tsx 와 별개로 페이지를 만들어야 함)

 

import Document, { DocumentContext } from "next/document";
import { ServerStyleSheet } from "styled-components";

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();
    }
  }
}

적용 후 화면.. 매우 잘 된다.

 

 

 

 

생각보다 쉽다

+ Recent posts