1-1. react-scripts
, react-router-dom
제거 (react
, react-dom
은 유지)
1-2. next
설치
1-3. script 에 next
관련 명령어 추가
- next dev
: localhost:3000 에서 dev mode 서버 동작
- next build
, next start
: production mode
2-1. CRA 에서는 public
폴더를 entry HTML file 로 사용하지만 Next.js 에서는 정적 자원을 위해 사용한다. 따라서 기존 image, font 등의 정적 자원을 public 폴더로 이동시킨다.
2-2. index.html 을 Next.js 로 변경한다.
- <head>
태그를 _document.js
파일로 이동
- 페이지간 재사용되는 레이아웃은 _app.js
파일로 이동
2-3. .next
파일을 gitignore 에 추가한다.
<html>
, <body>
태그를 업데이트 할 수 있다._document.js
파일을 추가한다.import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
<Html>
, <Head />
, <Main />
and <NextScript />
는 필수 구성 요소componentDidCatch
를 사용한 error handling// import App from 'next/app'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
Component
prop 은 활성화된 page
에 해당pageProps
는 초기 props 에 해당하는 객체CRA 에서는 React Router 라는 서드파티 라이브러리를 사용하지만 Next.js 는 페이지 라우팅을 파일 시스템을 기반으로 제공한다.
pages
라는 폴더에 파일이 추가되면 자동으로 라우터가 된다.
-Route
Component 를 pages
폴더 하위로 이동시킨다.
Index routes
pages/index.js
→ /
pages/blog/index.js
→ /blog
Nested routes
pages/blog/first-post.js
→ /blog/first-post
Dynamic route segments
pages/blog/[slug].js
→ /blog/:slug
(/blog/hello-world)pages/[username]/settings.js
→ /:username/settings
(/foo/settings)pages/post/[...all].js
→ /post/*
(/post/2020/id/title)react-helmet
라는 서드파티 라이브러리를 사용하여 meta tag 를 추가하지만 Next.js 에서는 next/head
를 사용한다.