npm i styled-components
npm i @types/styled-components -D
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()
}
}
}
를 _document.tsx에 입력한 후에
바벨을 설정할 수 있는 .babelrc를 만들고 수정
실제 적용이 되었는지를 확인하기 위해 index.tsx를 변경해줌
잘 적용된 것을 확인
스타일드 컴포넌트는 템플릿 리터럴을 사용하기 때문에 ``안에 css 및 scss코드를 작성하여 컴포노늩에 스타일을 줌 (scss는 sass (신텍티칼리 어섬 스타일 시트)로 부터 나옴)
서버 사이드에서 스타일링이 잘 적용되었는지 확인하기 위해 크롬브라우저에서 개발자도구를 통해서버에서 보내준 뷰를 확인할 수 있음
스타일드 컴포넌트에서 제공하는 createGlobalStyle 함수를 이용하여 글로벌 스타일을 생성해서 App 컴포넌트에 넣어줄 것
여기서 'styled-reset'이라는 라이브러리를 활용하여 기존 html의 스타일을 간편하게 제거하여 사용하도록 함
스타일을 리셋하는 이유는 브라우저 별로 각각 태그에 대한 기본 스타일이 다르고 각 스타일을 고려하지 않을 수 있기 때문에 리셋함으로써 스타일링에 편리함을 얻을 수 싱ㅆ음
styles/GlobalStyle.ts 파일을 생성 후에
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
body {
margin : 0;
}
`;
export default GlobalStyle;
테스트 겸으로 margin을 제거해봄
그 후 Pages/_app.tsx
import "@/styles/globals.css";
import type { AppProps } from "next/app";
import GlobalStyle from "../styles/GlobalStyle";
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<GlobalStyle />
<Component {...pageProps} />
</>
);
}
만들어둔 글로벌 스타일을 Component와 함께 return함
글로벌 스타일을 리셋하는 방법으로는 앞의 body처럼 각각의 값을 설정해주는 방법도 존재하지만
번거로운 작업이기 때문에 만들어둔 스타일셋이 없다면 `styled-reset'을 사용하면 됨
npm i styled-reset
을 설치후에
styled-reset을 임포트 한 후 글로벌 스타일 안에 추가해주기만 하면 스타일이 적용
코드는 아래 참조
pages/_document.tsx에서 구글폰트 CDN을 활용하여 네트워크로 받아오는 link 태그를 넣어줌
import Document, { DocumentContext, Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
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();
}
}
render() {
return (
<Html>
<Head>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap" rel="stylesheet" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
그 후 글로벌 스타일에 font-family 속성을 적용해주면 됨
import { createGlobalStyle, css } from "styled-components";
import reset from "styled-reset";
const globalStyle = css`
${reset};
* {
box-sizing: border-box;
}
body {
font-family: Noto Sans, Noto Sans KR;
}
`;
const GlobalStyle = createGlobalStyle`
${globalStyle}
`;
export default GlobalStyle;