コンテンツにスキップ
App RouterGetting StartedImage Optimization

画像の最適化

Next.js の <Image> コンポーネントは、HTML の <img> 要素を拡張して、次の機能を提供します。

  • サイズ最適化:各デバイスに最適なサイズの画像を自動的に提供し、WebP のような最新の画像フォーマットを使用します。
  • 視覚的な安定性:画像読み込み時の レイアウトシフトを自動的に防止します。
  • 高速なページ読み込み:ネイティブブラウザの遅延読み込みを使用して、画像がビューポートに入るときにのみ画像を読み込みます。オプションでぼかしプレースホルダーも使用できます。
  • アセットの柔軟性:リモートサーバーに保存されている画像でも、オンデマンドで画像をリサイズします。

<Image> の使用を開始するには、next/image からインポートし、コンポーネント内でレンダリングします。

app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return <Image src="" alt="" />
}

src プロパティは、ローカルまたはリモートの画像にすることができます。

🎥 Watch: next/image の使用方法についてさらに詳しく学ぶ → YouTube (9分)

ローカル画像

public という名前のフォルダをルートディレクトリに作成し、画像やフォントなどの静的ファイルを保存できます。public 内のファイルは、ベース URL (/) から始まるコードで参照できます。

Folder structure showing app and public folders
app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

静的にインポートされた画像の場合、Next.js は自動的に本来の widthheight を決定します。これらの値は、画像の比率を決定し、画像読み込み中の Cumulative Layout Shift を防止するために使用されます。

app/page.tsx
import Image from 'next/image'
import ProfileImage from './profile.png'
 
export default function Page() {
  return (
    <Image
      src={ProfileImage}
      alt="Picture of the author"
      // width={500} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  )
}

リモート画像

リモート画像を使用するには、src プロパティに URL 文字列を指定します。

app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="https://s3.amazonaws.com/my-bucket/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

Next.js はビルドプロセス中にリモートファイルにアクセスできないため、widthheight、およびオプションの blurDataURL プロパティを、手動で指定する必要があります。widthheight は、画像の正しいアスペクト比を推測し、画像読み込み時のレイアウトシフトを回避するために使用されます。または、fill プロパティを使用して、画像を親要素のサイズに合わせて埋め込むこともできます。

リモートサーバーからの画像を安全に許可するには、next.config.js でサポートされている URL パターンのリストを定義する必要があります。悪意のある使用を防ぐために、できるだけ具体的に指定してください。たとえば、次の構成は、特定の AWS S3 バケットからの画像のみを許可します。

next.config.ts
import type { NextConfig } from 'next'
 
const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
        search: '',
      },
    ],
  },
}
 
export default config

APIリファレンス

Next.js Image の全機能については、API リファレンスを参照してください。