styled-compnents 서버사이드 렌더링
https://github.com/vercel/next.js/tree/master/examples/with-styled-components
https://styled-components.com/docs/advanced#server-side-rendering
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
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()}
</>
),
};
} catch (error) {
console.error(error);
} finally {
sheet.seal();
}
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<script src="https://polyfill.io/v3/polyfill.min.js?features=default%2Ces2015%2Ces2016%2Ces2017%2Ces2018%2Ces2019" />
//적용 이유 :
react는 기본적으로 ES6이상 문법을 사용하기 때문에 구형 브라우저 특히 IE에서 호환이 안되는 경우 발생한다
Promise, window.fetch, Symbol, Object.assign, Array.from + [ IE9 Map, Set ]와 같은 필요한 것만 포함하고 있어 사이즈가 작아 가벼운 게 특징
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
nextjs 에서 스타일드 컴포넌트를 사용하면 새로고침시 적용이 안되어 서버사이드 렌더링을 설정해야한다.
next 공홈, 스타일드 컴포넌트 문서에 보면 적용 예시 방법이 있음.
styled components는 따로 SSR 세팅(_document.js)을 안 하면 서버사이드 렌더링이 안 됩니다.
동적으로 스타일 태그를 생성하기 때문입니다.
Promise, window.fetch, Symbol, Object.assign, ]
// 바벨로 처리가 되지 않아서 babel-pollyfill.io, 라이브 러리 사용