[next.js 13] styled-components, 폰트 설정하기

적자생존·2023년 1월 11일
1

next.js

목록 보기
2/6

1. next.js 13

next.js 13버전이 나왔다.

12버전을 체험했기에 13버전을 체험해보기로 해서 프로젝트를 설치하고 next+typescript를 설치하였다.

그런데 styled-components로 css작업을 하고 npm run dev해서 확인하고 새로고침하면 css가 다 날라가는 현상이 발생하였다.

그래서 찾아본 결과

2. styled-components 설정

app루트를 이용하지 않고 pages를 이용(기존 next 방식)

app루트 방식은 아직 베타버전으로 불안정해서 좀,,,

_document.tsx

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();
    }
  }
}

로 수정하고

_app.tsx

import { ThemeProvider, DefaultTheme } from "styled-components";

const theme: DefaultTheme = {
  colors: {
    primary: "#111",
    secondary: "#0070f3",
  },
};


return(
<ThemeProvider theme={theme}>
	<GlobalStyle />
	<Component {...pageProps} />
</ThemeProvider>
)

componet를 ThemeProvider로 감싸준다.

3. 폰트 적용하기

구글 폰트와 로컬 폰트가 있다

구글 폰트의 경우 next에 내장된 폰트로 구글에서 제공하는 폰트이다.

로컬 폰트는 말그대로 내가 다운로드 한 폰트이다.

가. 구글폰트

app.tsx

import { Work_Sans } from "@next/font/google";

const workSans = Work_Sans({
   subsets: ["latin"],
   weight: "800",
 });

// 생략

return(
<main className={workSans.className}>
            <Component {...pageProps} />
</main>
)

위 처럼 사용할 수 있다.

나. 로컬 폰트

import localFont from "@next/font/local";

const myFont = localFont({
  src: "../public/fonts/SpoqaHanSansNeo-Regular.otf",
});

<main className={myFont.className}>
            <Component {...pageProps} />
</main>

위 처럼 수정해서 사용하면 적용이 된다.

profile
적는 자만이 생존한다.

0개의 댓글