画像の最適化
Next.js の <Image> コンポーネントは、HTML の <img> 要素を拡張し、以下の機能を提供します。
- サイズ最適化:各デバイスに最適なサイズの画像を、WebP などの最新の画像フォーマットを使用して自動的に提供します。
- 視覚的な安定性:画像の読み込み時に、レイアウトシフト を自動的に防ぎます。
- 高速なページ読み込み:ネイティブブラウザの遅延読み込みを使用して、ビューポートに入った画像のみを読み込みます。オプションでぼかし効果のあるプレースホルダーも利用できます。
- アセットの柔軟性:リモートサーバーに保存されている画像でも、オンデマンドでサイズ変更できます。
<Image> を使用するには、next/image からインポートし、コンポーネント内でレンダリングします。
import Image from 'next/image'
export default function Page() {
return <Image src="" alt="" />
}src プロパティは、ローカルまたはリモートの画像にすることができます。
🎥 視聴:
next/imageの使用方法についてさらに詳しく学ぶ → YouTube (9分)。
ローカル画像
静的ファイル(画像やフォントなど)は、ルートディレクトリの public という名前のフォルダに保存できます。public 内のファイルは、ベース URL (/) から始まるコードで参照できます。

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 は自動的に本来の width と height を決定します。これらの値は、画像の縦横比を決定し、画像読み込み中の Cumulative Layout Shift を防ぐために使用されます。
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 文字列を指定できます。
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 はビルドプロセス中にリモートファイルにアクセスできないため、width、height、およびオプションの blurDataURL プロパティを手動で指定する必要があります。width と height は、画像の正しいアスペクト比を推測し、画像読み込み時のレイアウトシフトを防ぐために使用されます。あるいは、fill プロパティを使用して、画像を親要素のサイズに合わせることもできます。
リモートサーバーからの画像を安全に許可するには、next.config.js でサポートされている URL パターンのリストを定義する必要があります。悪意のある使用を防ぐために、できるだけ具体的に指定してください。たとえば、以下の構成では、特定の AWS S3 バケットからの画像のみが許可されます。
import type { NextConfig } from 'next'
const config: NextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 's3.amazonaws.com',
port: '',
pathname: '/my-bucket/**',
search: '',
},
],
},
}
export default configAPIリファレンス
役に立ちましたか?
