画像変換は、Next.js の <Image /> コンポーネント ↗ と自動で連携できます。
画像変換を使うには、グローバルな画像ローダーを定義するか、各 <Image /> コンポーネント向けにカスタムローダーを複数定義します。
Next.js は、width と quality の正しいパラメーター付きで画像をリクエストします。
画像変換側でキャッシュし、クライアントに最適なフォーマットを配信します。
アプリ内の すべての 画像で Images を使うには、アプリ向けのグローバル loaderFile ↗ を定義します。
Next.js アプリケーションのルートにある next.config.js ファイルに、次の設定を追加します。
module.exports = {
images: {
loader: "custom",
loaderFile: "./imageLoader.ts",
},
};次に、指定したパス(Next.js アプリケーションのルートからの相対パス)に imageLoader.ts ファイルを作成します。
import type { ImageLoaderProps } from "next/image";
const normalizeSrc = (src: string) => {
return src.startsWith("/") ? src.slice(1) : src;
};
export default function cloudflareLoader({
src,
width,
quality,
}: ImageLoaderProps) {
const params = [`width=${width}`];
if (quality) {
params.push(`quality=${quality}`);
}
if (process.env.NODE_ENV === "development") {
return `${src}?${params.join("&")}`;
}
return `/cdn-cgi/image/${params.join(",")}/${normalizeSrc(src)}`;
}または、各 <Image /> コンポーネントにローダーを定義します。
import Image from "next/image";
const normalizeSrc = (src) => {
return src.startsWith("/") ? src.slice(1) : src;
};
const cloudflareLoader = ({ src, width, quality }) => {
const params = [`width=${width}`];
if (quality) {
params.push(`quality=${quality}`);
}
if (process.env.NODE_ENV === "development") {
return `${src}?${params.join("&")}`;
}
return `/cdn-cgi/image/${params.join(",")}/${normalizeSrc(src)}`;
};
const MyImage = (props) => {
return (
<Image
loader={cloudflareLoader}
src="/me.png"
alt="Picture of the author"
width={500}
height={500}
{...props}
/>
);
};