이번 포스팅은 Next.js에 styled-components를 적용할 때 가장 기본적인 설정 2가지를 정리해보려 한다.
Next.js로 프로젝트를 구성하는 도중, styled-components를 적용하여도 새로고침하면 css가 풀리는 현상을 마주하였다..! 😬
현상의 이유는 Next.js가 SSR로 작동하기 때문에 style이 들어가기도 전에 렌더링이 되는 것이다.
따라서 아래의 방법으로 쉽게 SSR 단계에서 CSS를 적용할 수 있다.
npm i babel-plugin-styled-components -D
.babelrc
를 생성한다.{
"presets": ["next/babel"],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}
_documents.js
를 생성하여 하기 코드를 붙여넣는다.// _documents.js
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>
<style />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
전역 CSS 적용은 대체로 React와 동일하다.
createGlobalStyle
를 사용하여 GlobalStyle를 생성한다.// reset.js
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
body {
background: #000;
}
`
_app.js
에 GlobalStyle을 적용시킨다.// _app.js
import GlobalStyle from 'styles/reset';
function MyApp({ Component, pageProps }) {
return (
<>
<GlobalStyle />
<Component {...pageProps} />
</>
);
}
export default MyApp;
위 두가지 방법으로 styled-components를 next.js에 기본적으로 설정해야하는 것을 알아보았다. 👏