반응형
NextJS에서 styled-components를 사용하는 도중에 심한 깜빡거림 현상으로 인해 작성하게 되었습니다.
styled-components는 다크모드 구현을 위해 사용하게 되었습니다.
npm
$ npm install --save styled-components
$ npm install -D @types/styled-components
$ npm install -D babel-plugin-styled-components
typescript를 사용하고 있기 때문에 @types를 받아왔습니다.
_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'
import Document, { DocumentContext, DocumentInitialProps } from 'next/document'
import { ServerStyleSheet } from "styled-components";
class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
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 lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
styles: [] 이 부분입니다.
NextJS Customizing renderPage 바로가기 ( Vercel )
그리고 styled-components를 사용하면 스타일 적용전에 렌더가 되면서 에러가 발생한다고 합니다.
그래서 위에서 install해준 .babel을 작성해줍니다.
.babelrc ( root경로에 생성합니다. )
{
"presets": ["next/babel"],
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true,
"displayName": false
}
]
]
}
반응형
'React > NextJS' 카테고리의 다른 글
[ NextJS ] NextJS에서 editorJS 사용하기 ( 기본설정 ) (0) | 2023.04.05 |
---|---|
[ NextJS ] router.query에 관하여 (0) | 2023.03.31 |
[ NextJS ] Uncaught TypeError: Cannot read properties of null (reading 'default') (0) | 2023.03.23 |
[ NextJS ] unhandledRejection: Error: Cannot find module ... (0) | 2023.03.16 |
[ NextJS ] Build optimization failed: found pages without a React Component as default export in (0) | 2023.03.16 |