본문 바로가기

project

[React] 인스타 클론코딩 기록 (4-1) - css 서버사이드렌더링

front에 

npm i babel-plugin-styled-components

설치 해주고요

 

파일 .babelrc 생성

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

확인

next/babel은 이미 깔려있다는 가정

 

모든 페이지의 공통요소인 _app.js 에 먹이고 싶은데 어떻게?

그 상위의 요소인 _document.js를 pages 디렉토리 안에 생성

import React from 'react';
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 />
            <body>
                <script src="https://polyfill.io/v3/polyfill.min.js?features=default%2Ces2015%2Ces2016%2Ces2017%2Ces2018%2Ces2019" />
                <Main />
                <NextScript />
            </body>
        </Html>
    );
  }
}

Html, Head 다 대문자로 쓰면서 body만 소문자로 쓰는 신기한...

이 친구는 class로 작성합니다. 이걸 아직 hooks로 바꾸는게 없는것 같다네요.

 

다른 페이지들에서는 안쓰지만 아직 _document.js, _app.js 에서는 getInitialProps를 사용합니다.

저 두 페이지에서만 쓰는 특수한 서버사이드렌더링이라고만 생각하면 됩니다.

다른 페이지는 다 getServerSideProps, getStaticProps 씁니다.

 

바벨은 es5에 존재하지 않는 es6의 메서드나 생성자들까지 지원해주지는 않습니다. (Promise, Set)

그래서 es5로 동작하는 하위 브라우저(IE)를 지원하는 서비스를 개발할 때에는 폴리필을 추가하도록 합니다.

가운데 script가 polyfill.io/ 에서 제공해주는 IE를 위한 그것입니다. <NextScript />보다 위에 써주면 됩니다.

 

styled-components에서 이렇게 css 서버사이드렌더링을 하라고 안내한 내용이었습니다.