Cloudflare
操作指南
图像优化

图像优化

Next.js 内置了一个 <Image> 组件 (opens in a new tab),可自动优化图像以加快页面加载速度。要启用图像优化,您必须定义图像绑定或使用自定义加载器。

使用 Cloudflare Images 绑定

Cloudflare 适配器使用 Cloudflare Images (opens in a new tab) 提供了一个与 Next.js 兼容的图像优化 API,可以通过 next.config.js (opens in a new tab) 进行配置。

必须定义 IMAGES 绑定才能启用图像优化:

// wrangler.jsonc
{
  "images": {
    "binding": "IMAGES",
  },
}

图像优化可能会产生额外费用。请参阅 Cloudflare Images 定价 (opens in a new tab) 了解详情。

兼容性说明

  • 仅支持 PNG、JPEG、WEBP、AVIF、GIF 和 SVG。不支持的图像将未经优化原样返回。
  • 不支持 minimumCacheTTL 配置 (opens in a new tab)。所有资产(静态、本地或远程)均被视为不可变(永久缓存)或可变。除了 immutable 属性外,它不尊重非静态图像的 Cache-Control 头设置的缓存行为。
  • 不支持 dangerouslyAllowLocalIP 配置 (opens in a new tab)。如果 remotePatterns 配置允许该 URL,则始终允许本地 IP 地址。

使用自定义加载器

您首先需要为您的区域 启用 Cloudflare Images (opens in a new tab)

强烈建议将可转换的图像来源限制为托管图像的位置,例如 R2 存储桶 (opens in a new tab)

然后您需要配置 Next 应用程序以使用 Cloudflare Images 的自定义加载器。

在应用程序根目录下创建 image-loader.ts

// image-loader.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") {
    // 在使用 `next dev` 时提供原始图像
    return `${src}?${params.join("&")}`;
  }
  return `/cdn-cgi/image/${params.join(",")}/${normalizeSrc(src)}`;
}
⚠️

此简单加载器不尊重 Next.js remotePatterns (opens in a new tab)。您应该 在仪表板中配置 允许的来源 (opens in a new tab)

然后您需要更新应用程序配置以使用此加载器:

// next.config.ts
import type { NextConfig } from "next";
 
const nextConfig: NextConfig = {
  // ...
  images: {
    loader: "custom",
    loaderFile: "./image-loader.ts",
  },
};
 
export default nextConfig;

使用 cloudflare 加载器的图像将直接提供,无需经过中间件。

请参阅 Cloudflare Images 文档 (opens in a new tab) 了解更多详情。