Next.js 에서 styled-components를 사용하려면 설정이 필요하다
styled-components는 CSR로 작동하기 때문에 SSR에 style이 적용되도록 하기 위한 설정이다.
1. Install styled-components
yarn add styled-components
2. Install babel-plugin-styled-components
yarn add -D babel-plugin-styled-components
3. Create a new file ".babelrc" under the root directory
{
"presets": ["next/babel"],
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true, // SSR을 위한 설정
"displayName": true, // 클래스명에 컴포넌트 이름을 붙임
"pure": true // dead code elimination (사용되지 않는 속성 제거)
}
]
]
}
Next.js 깃헙 참고
https://github.com/vercel/next.js/blob/deprecated-main/examples/with-styled-components/.babelrc
4. Create a new file "_document.js" under the pages
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()}
</>
),
};
} finally {
sheet.seal();
}
}
render() {
return (
<Html>
<Head>
<link rel="icon" href="/blogger.png" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
custom document는 아래 링크 참고
https://nextjs.org/docs/advanced-features/custom-document