Next.js 로 프로젝트 시작하기

102·2022년 10월 26일
0

Next.js

목록 보기
1/3

🚀 create next-app 으로 Next.js 시작하기

yarn create next-app --typescript

뒤에 타입스크립트를 적지않으면 기본 js파일로 생성된다.

명령어를 적으면 프로젝트 이름을 적으라고 한다.
프로젝트 이름을 적고 엔터를 쳐주면 알아서 프로젝트 생성이 된다 !!

next.js 실행

yarn dev

🌼 styled-components 적용하기

yarn add styled-components

나는 글로벌 스타일과 자주쓰는 컬러는 테마로 빼서 쓸것이라서 두개의 파일을 만들어 줬다.

//Theme.js

const Theme = {
	// 테마로 쓸 코드
}

export default Theme;
//GlobalStyles.js

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
	// 공통 스타일 코드    
`

export default GlobalStyle

그리고 요 테마와 공통스타일을 적용해준다

//_app.tsx

import type { AppProps } from "next/app";
import { ThemeProvider } from "styled-components";
import Theme from "../styles/Theme";
import GlobalStyle from "../styles/GlobalStyles";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ThemeProvider theme={Theme}>
      <GlobalStyle />
      <Component {...pageProps} />
    </ThemeProvider>
  );
}

export default MyApp;

오마이갓쉬 하다보니 styled components에서 오류가 났다.

Prop className did not match. Server: ~~ 이런 오류가 발생했는데 구글링을 조금 해보니
next.js 는 서버사이드 렌더링을 하기때문에 처음 서버에서 생성된 클래스네임과 클라이언트의 클래스네임이 달라서 나는 오류라고 한다.

환경에 따라 다르게 나타나는 className을 일관성 있게 해주는 babel-plugin-styled-components를 다운받아보자

yarn add -D babel-plugin-styled-components

그리고 루트 디렉토리에 .babelrc 파일을 만들어 아래와 같은 내용을 적어준다.

{
  "presets": ["next/babel"],
  "plugins": [
    [
      "babel-plugin-styled-components", 
      {
        "ssr": true, // SSR을 위한 설정
        "displayName": true, // 클래스명에 컴포넌트 이름을 붙임
        "pure": true // dead code elimination (사용되지 않는 속성 제거)
      }
    ]
  ]
}

🌝 layout 적용하기

내가 현재 만드려는 페이지는 배경이 계속 같기때문에 layout으로 감싸서 모든 페이지에서 동일한 레이아웃을 가지도록 해줄것이다.

//Layout.tsx

const Layout = ({ children }) => {
  return (
    //공통으로 들어갈 레이아웃의 코드
  );
};

export default Layout;

공통으로 들어갈 코드를 작성한 후 __app.tsx 파일에 Layout으로 감싸준다.

//__app.tsx

import type { AppProps } from "next/app";
import { ThemeProvider } from "styled-components";
import Theme from "../styles/Theme";
import GlobalStyle from "../styles/GlobalStyles";
import Layout from "./Layout";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ThemeProvider theme={Theme}>
      <GlobalStyle />
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </ThemeProvider>
  );
}

export default MyApp;

0개의 댓글