_document.tsx 에러 상황

Jacob You·2022년 5월 26일
0

문제

Next.js 를 사용해서 작업을 할 때, SSR 상황에서 스타일 적용이 늦는 경우가 있다. (styled-components 를 사용할 때) 그럴 때를 위해서 _document.tsx 를 커스텀해서 사용한다. 오늘은 그동안 잘 써먹던 보일러 플레이트에서 문제가 발생한 케이스를 다뤄보고자 한다.

개발환경의 변화

내가 애용하는 보일러 플레이트는 react v17과 next v12 환경에서 작성되었다. 그러던 사이에 리액트는 v18 이 나왔고 next 의 경우도 마이너버전 업데이트가 있었다.

에러메시지

Class static side 'typeof MyDocument' incorrectly extends base class static side 'typeof Document'.
  The types returned by 'getInitialProps(...)' are incompatible between these types.
    Type 'Promise<{ styles: Element; html: string; head?: (Element | null)[] | undefined; }>' is not assignable to type 'Promise<DocumentInitialProps>'.
      Type '{ styles: JSX.Element; html: string; head?: (JSX.Element | null)[] | undefined; }' is not assignable to type 'DocumentInitialProps'.
        Type '{ styles: JSX.Element; html: string; head?: (JSX.Element | null)[] | undefined; }' is not assignable to type '{ styles?: ReactElement<any, string | JSXElementConstructor<any>>[] | ReactFragment | undefined; }'.
          Types of property 'styles' are incompatible.
            Type 'Element' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>[] | ReactFragment | undefined'.

이러한 코드에서 MyDocument 부분에서 저런 에러가 나기 시작했다. 리액트 버전을 17로 낮춰보고 별짓을 다 해봤는데 없어지질 않는다. 검색해도 잘 나오지 않는다.

실마리

https://github.com/vercel/next.js/issues/36008 여기에서 답을 얻었다. 리액트 버전이 올라가면서 뭔가 버그가 생긴 거 같은데 결론은

styles: (
  <>
    {initialProps.styles}
    {sheet.getStyleElement()}
  </>
),

부분을

styles: [
  <>
    {initialProps.styles}
    {sheet.getStyleElement()}
  </>
],

고치고 나서 에러가 발생하지 않았다. 솔직히 원리는 잘 모르겠으나 어째뜬 빨간줄이 사라지고 다시 작업을 할 수 있게 되었다. 하면 할수록 어려운 게 타입스크립트 인듯 싶다.

profile
야매로 먹고사는 프론트엔드 개발자

0개의 댓글