コンテンツにスキップ

画像の最適化

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 プロパティは、ローカルまたはリモートの画像にすることができます。

🎥 視聴: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 リファレンスを参照してください。