Cloudflare
操作指南
图片优化

图片优化

Next.js 内置了 <Image> 组件 (opens in a new tab),可以自动优化图片以加快页面加载速度。

本文将介绍如何将 Next.js 的图片优化功能与 Cloudflare Images (opens in a new tab) 集成。

启用 Cloudflare Images

首先需要为你的区域启用 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) {
  if (process.env.NODE_ENV === "development") {
    // 在使用 `next dev` 时返回原始图片
    return src;
  }
  const params = [`width=${width}`];
  if (quality) {
    params.push(`quality=${quality}`);
  }
  const paramsString = params.join(",");
  return `/cdn-cgi/image/${paramsString}/${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)