Next.js 12 は、パフォーマンス向上や新機能が数多く追加されていますので、 Next.js 12 の主要な新機能を紹介します。
目次
- 新しいコンパイラ: Rust を使った SWC
- AVIF 画像形式サポート
- URL Imports
- Middleware のサポート
- Fine-grained Cache Control
- React 18 のサポート
1. 新しいコンパイラ: Rust を使った SWC
Next.js 12 では、Babel にかわって Rust 言語によって実装された SWC コンパイラが用意されています。ビルト速度とパフォーマンスが向上。
// next.config.js module.exports = { swcMinify: true, };
2. AVIF 画像形式サポート
Next.js 12 は最新の画像圧縮フォーマット、AVIF をサポートしています。これにより画像の読み込みが高速化され、体感速度が向上します。
//<Image>.tsx import Image from 'next/image'; export default function MyImage() { return ( <Image src="/example.png" alt="Example Image" width={500} height={500} formats={['avif', 'webp', 'jpeg']} /> ); }
3. URL Imports
ES Modules のインポートを URL 行うことができます。これにより、npm や yarn を使用せずにライブラリを使用することが可能です。
// Importing 'lodash' from a URL import _ from 'https://cdn.skypack.dev/lodash';
4. Middleware のサポート
Next.js 12 では Middleware を導入しました。これにより、_app.tsx のラッパーコンポーネント内で初期化されていた処理を Middleware に移行することができます。
// pages/_middleware.ts import { NextRequest, NextResponse } from 'next/server'; export function middleware(req: NextRequest) { // Request header を検査 if (req.headers.get('user-agent')?.match(/puppeteer/i)) { return NextResponse.rewrite('/puppeteer-detected'); } return NextResponse.next(); }
5. Fine-grained Cache Control
Next.js 12 では新しいキャッシュコントロールシステムが導入されました。これにより、キャッシュの挙動をより細かく制御することができます。
// pages/_middleware.ts import { NextRequest, NextResponse } from 'next/server'; export function middleware(req: NextRequest) { // レスポンスキャッシュを 1 時間に設定 return new NextResponse(null, { ttl: 3600 }); }
6. React 18 のサポート
Next.js 12 は、React Server Components や Suspense などの新機能を含む React 18 のアルファリリースをサポートしています。
// pages/index.tsx import React, { Suspense } from 'react'; const MyComponent = React.lazy(() => import('./MyComponent')); export default function IndexPage() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <MyComponent /> </Suspense> </div> ); }
これらの新機能を活用して、Next.js 12 のパフォーマンスを最大限に引き出し、素晴らしいウェブサイトやアプリケーションを作成しましょう。