21.10.27 업데이트 된 next.js 12의 업데이트 내용 정리하기.
npm i next@latest
또는
npm i next@12
Rust
컴파일러로 대체함 : 프로젝트 빌드 속도 증가, 새로고침 속도 증가.<Image />
AVIF 지원 : webP보다 20% 압출률이 더 좋은 AVIF 포맷 지원.Rust
컴파일러로 대체하면서
// next.config.js
module.exports = {
swcMinify: true
}
미들웨어 처리가 가능한 기능 추가 됨.
미들웨어를 사용하기 위한 파일 생성
// pages/_middleware.js
export function middleware(req, ev) {
return new Response('Hello, world!')
}
React 18를 적용하면서 Suspense
, startTransition
의 기능을 사용할 수 있다
npm install next@latest react@rc react-dom@rc
// next.config.js
module.exports = {
experimental: {
concurrentFeatures: true
}
}
Suspense
및 SSR 스트리밍
을 사용할 수 있다.import dynamic from 'next/dynamic'
import { lazy, Suspense } from 'react'
import Content from '../components/content'
// These two ways are identical:
const Profile = dynamic(() => import('./profile'), { suspense: true })
const Footer = lazy(() => import('./footer'))
export default function Home() {
return (
<div>
<Suspense fallback={<Spinner />}>
{/* A component that uses Suspense-based */}
<Content />
</Suspense>
<Suspense fallback={<Spinner />}>
<Profile />
</Suspense>
<Suspense fallback={<Spinner />}>
<Footer />
</Suspense>
</div>
)
}
getServerSideProps
또는 getStaticProps
등의 코드도 더 이상 필요하지 않게 된다고 한다// next.config.js
module.exports = {
experimental: {
concurrentFeatures: true,
serverComponents: true
}
}
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
.server.js
로 변경하여 서버용 컴포넌트를 만들고, 서버용 컴포넌트 내부에서 직접 클라이언트 컴포넌트를 가져올 수 있다..server.js
을 파일 이름 끝에 추가./pages/home.server.js
.client.js
를 추가./components/avatar.client.js
<Home>
은 항상 SSR, <Profile>
은 클라이언트로 스트리밍되며, 클라이언트 런타임에 포함되지 않는다. <Content>
은 클라이언트 측에서 Hydration 됨.// pages/home.server.js
import { Suspense } from 'react'
import Profile from '../components/profile.server'
import Content from '../components/content.client'
export default function Home() {
return (
<div>
<h1>Welcome to React Server Components</h1>
<Suspense fallback={'Loading...'}>
<Profile />
</Suspense>
<Content />
</div>
)
}
URL 자체로 외부 모듈을 Import를 할 수 있는 기능
module.exports = {
experimental: {
urlImports: ['https://cdn.skypack.dev']
}
}
// 또는
import confetti from 'https://cdn.skypack.dev/canvas-confetti'
Next.js가 페이지를 렌더랑 하는 방법에는 static generation과 server-side rendering 방식이 있다.
ISR(Incremental Static Generation):
getStaticProps
함수를 활용한static generation
방식은 언제나 빌드 시점 에 페이지를 생성하지만, ISR 방식은 일정 주기마다 데이터의 최신 여부를 검사하고 업데이트된 데이터로 페이지를 다시 생성한다
ISR로 작성된 페이지에서 fallback : true
로 설정되게 되면
Next.js 12에서
이미지 압축 포맷 AVIF라는 형식을 <Image>
태그에서 옵션으로 사용할 수 있다.
module.exports = {
images: {
formats: ['image/avif', 'image/webp']
}
}
브라우저가 AVIF를 지원할 때만 정상적으로 제공이 되고, 그렇지 않으면 WebP를 지원하는지 판단 후 WebP를 제공하는 방식이다. 모두 제공되지 않으면 원본 이미지 형식이 제공된다.