3. Next.js์™€ styled-components


๐Ÿค”ย ๋ญ๊ฐ€ ๋ฌธ์ œ์ง€โ€ฆ?

๊ทธ๋ƒฅ ์ƒ๊ฐ ์—†์ด โ€œ์ž˜ ์ ์šฉ๋˜๊ฒ ์ง€?โ€ ํ•˜๊ณ  CRA์—์„œ์™€ ๊ฐ™์ด ํ‰์†Œ๋Œ€๋กœ styled-components๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.
๊ทผ๋ฐ, ๋‚ด๊ฐ€ ์ ์šฉํ•œ CSS๊ฐ€ ์ ์šฉ๋˜์ง€ ์•Š๋Š” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹คโ€ฆ

๋ถ„๋ช… ์ด๋ ‡๊ฒŒ ๋– ์•ผ ํ•˜๋Š”๋ฐโ€ฆ

๋‚ด๊ฐ€ ์„ค์ •ํ•œ CSS

์ด๋ ‡๊ฒŒ ์•„๋ž˜์™€ ๊ฐ™์ด CSS๊ฐ€ ์ ์šฉ๋˜์ง€ ์•Š์€ ์ƒํƒœ์˜ raw ๋ฒ„ํŠผ์ด ๋ Œ๋”๋ง ๋˜๋Š” ๊ฒƒ์ด์—ˆ๋‹ค.

raw...

๋ถ„๋ช… ๋ญ”๊ฐ€ SSR ๋ฐฉ์‹์— ์˜ํ•œ ๋ฌธ์ œ์ผ ๊ฒƒ์ด๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹คโ€ฆ

Next.js๋Š” SSR ๋ฐฉ์‹์„ ๋”ฐ๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ์„œ๋ฒ„์—์„œ HTML์„ ๋ฏธ๋ฆฌ ๊ทธ๋ฆฐ ๋’ค, ๋ทฐ์— ๋„์›Œ์ค€๋‹ค. ๋”ฐ๋ผ์„œ pre-rendering ๊ณผ์ •์—์„œ styled-components๊ฐ€ ์ ์šฉ๋˜์ง€ ์•Š๋Š” ๋ฌธ์ œ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.

์ฆ‰, styled-components๊ฐ€ ์ ์šฉ๋˜๊ธฐ๋„ ์ „์— ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง ๋˜๋Š” ๊ฒƒ์ด ๋ฌธ์ œ๋ผ๊ณ  ๋ณธ ๊ฒƒ์ด๋‹ค.


๐Ÿ’Šย ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•


babel-plugin-styled-components ์„ค์น˜

1
$ npm install --save-dev babel-plugin-styled-components

babel ํŒŒ์ผ ์ƒ์„ฑํ•ด์ฃผ๊ธฐ

์ตœ์ƒ๋‹จ ๋ฃจํŠธ(root ๋””๋ ‰ํ† ๋ฆฌ)์— .babelrc ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์ค€๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ๋ฉด ๋œ๋‹ค!

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"presets": ["next/babel"],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}

_document.tsx ํŒŒ์ผ ์ƒ์„ฑ

pages ์•„๋ž˜์— _document.ts ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์ค€๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
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();
}
}
}

์—ฌ๊ธฐ๊นŒ์ง€ ํ•ด์ฃผ๋ฉด ๋ Œ๋”๋ง ์‹œ์—๋„ styled-components๊ฐ€ ์ž˜ ์ ์šฉ๋˜์–ด ๋ทฐ์— ๋‚˜ํƒ€๋‚˜๊ฒŒ ๋œ๋‹ค ๐Ÿ™‚


3. Next.js์™€ styled-components

https://hoonjoo-park.github.io/nextJS/3.nextjsAndSC/

Author

Hoonjoo

Posted on

2022-02-08

Updated on

2022-02-08

Licensed under

Comments