Next.js_basic

개발 공부 기록·2022년 1월 10일
0

Next.js

목록 보기
1/1
post-thumbnail

Next.js?

  • ReactSSR 가능하게 해주는 프레임워크 (SEO 가능)
  • 기본 정적 페이지 렌더링, 동적 페이지 렌더링도 가능
  • 서버 렌더링, 스태틱 익스포팅, CSS in JS, 제로 셋업를 기본으로 제공

Next.js 는 React 기반 Framework
폴더 및 파일 기반 Routing 지원하고, Server Side Rendering을 지원
즉, SEO 적용이 수월

특징

  1. 컴파일과 번들링이 자동 (webpack 과 babel)

  2. 자동 리프레쉬 기능으로 수정하면 화면에 바로 반영

  3. 서버사이드 렌더링 지원

  4. 정적 파일을 지원

설치

npm

npx create-next-app@latest [폴더명]

TypeScript
npx create-next-app@latest --ts [폴더명]

yarn

yarn create next-app [폴더명]

TypeScript
yarn create next-app --typescript [폴더명]

_app.js

// import App from 'next/app'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
//   // calls page's `getInitialProps` and fills `appProps.pageProps`
//   const appProps = await App.getInitialProps(appContext);
//
//   return { ...appProps }
// }

export default MyApp

Custom App

  • 페이지 전환 시 레이아웃/상태 값 유지 가능
  • componentDidCatch를 이용해 커스텀 에러 핸들링 가능
  • 추가적인 데이터를 페이지로 주입 가능
  • globals.css 선언
  • _app은 서버로 요청이 들어왔을 때 가장 먼저 실행되는 컴포넌트로, 페이지에 적용할 공통 레이아웃의 역할
  • 모든 컴포넌트에 공통으로 적용할 속성 관리
  • _app은 로직, 전역 스타일 등 컴포넌트에 공통 데이터를 다룸

_document.js

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

Custom Document

  • _document는 _app 다음에 실행되며, 공통적으로 활용할 <head> (Ex. 메타 태그)나 <body> 태그 안에 들어갈 내용들을 커스텀할때 활용
  • 폰트 임포트
  • charset, 웹 접근성 관련 태그 설정
  • _document는 공통적으로 적용할 HTML 마크업을 중심다룸
  1. _document를 작성할 때는 Document 클래스를 상속받는 클래스 컴포넌트로 작성해야만 하며, 렌더 함수는 꼭 <Html><Head>, <Main>, <NextScript> 요소를 리턴

  2. _document에서 사용하는 <Head> 태그는 next/head가 아닌 next/document 모듈에서 불러와야 하는데, _document<Head> 태그에는 모든 문서에 공통적으로 적용될 내용(Ex. charset, 뷰포트 메타태그 등)이 들어가야함

CSR/SSR

  • Next js 모든 페이지 사전 렌더링 (Pre-rendering)
    ⇒ 더 좋은 퍼포먼스
    ⇒ 검색 엔진 최적화(SEO)
  1. Static Generation 정적 생성
  2. Server Side Rendering (SSR, Dynamic Rendering)

차이점은 언제 html 파일을 생성하는가?

1. [정적 생성]

  • 프로젝트가 빌드하는 시점에 html파일들이 생성
  • 모든 요청에 재사용
  • 퍼포먼스 이유로, 넥스트 js는 정적 생성을 권고
  • 정적 생성된 페이지들은 CDN에 캐시
  • getStaticProps / getStaticPaths
export async function getStaticProps(context) {
  return { 
    // will be passed to the page component as props
    props: {},
  }
}

getStaticProps (정적 생성)

export async function getStaticPaths() {
  return {
    paths: [
      // See the "paths" section below
      { params: { ... } } 
    ],
    // See the "fallback" section below
    fallback: true, false, or 'blocking' 
  };
}

getStaticPaths(정적 생성)

  • e.g.) 마케팅 페이지, 블로그 게시물, 제품 목록, 도움말/문서 (미리 만들어 두는 경우)

2. [SSR]

  • 매 요청마다 html을 생성
  • 항상 최신 상태 유지
  • getServerSideProps
export async function getServerSideProps(context) {
  return {
    // will be passed to the page component as props
    props: {}, 
  }
}

getServerSideProps (SSR)

  • e.g.) 관리자 페이지, 분석 차트

_error.js

function Error({ statusCode }) {
  return (
    <p>
      {statusCode
        ? `An error ${statusCode} occurred on server`
        : 'An error occurred on client'}
    </p>
  )
}

Error.getInitialProps = ({ res, err }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404
  return { statusCode }
}

export default Error

Error Page

  • 500 server 에러 페이지
  • 404 static 클라이언트 에러도 처리가능

.env

// node.js

process.env.변수명

// next.js

process.env.NEXT_PUBLIC_변수명

pages/api

export default function handler(req, res) {
  const { pid } = req.query
  res.end(`Post: ${pid}`)
}

Dynamic API Routes

  • 클라이언트에서 간단한 rest api 설정 가능
profile
둔필승총(鈍筆勝聰) - 기억보다는 기록을

0개의 댓글