优化 Next.js 上的图片加载
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
默认情况下,除非您明确将 images.unoptimized
设置为 false 或使用自定义 Image Loader,否则内置 Next.js 图片优化会在 App Hosting 上停用。
您可以配置 Next.js 全局图片加载器,并使用图片处理 Firebase 扩展程序在 App Hosting 上按需优化和交付 Next.js 应用中的图片。
前提条件
- 您拥有 Firebase 项目和 App Hosting 后端。
- 您的项目中已启用 Cloud Storage。
- 您的项目中已启用 Cloud Functions for Firebase。
安装扩展程序
前往 Firebase Extensions Hub 中的图片处理扩展程序,然后选择 在 Firebase 控制台中安装。按照屏幕上的说明操作。
如果您的应用使用本地图片,并且您想使用此扩展程序对其进行优化,则需要在扩展程序安装过程中配置“主机名”参数。
在扩展程序配置期间:当您到达“配置扩展程序”这一步时,找到“主机名”参数。
设置主机名:输入 Firebase App Hosting 后端的默认网域。此网域通常以 .hosted.app
结尾。
安装完成后,图片处理 API 应部署为 Cloud Functions 中的函数。在 Firebase 控制台中前往函数信息中心,然后复制图片处理 API 触发器网址。
设置自定义图片加载器
创建一个图片加载器,该加载器针对每个优化后的图片组件使用已部署的图片处理 API。为了进行优化,请重写该应用,使其在同一 Firebase App Hosting 网域下提供,并缓存到与 Next.js 应用相同的全球 CDN 后面。
首先,将以下字段添加到 next.config.js
文件中:
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
loader: "custom",
loaderFile: "./loader.js",
},
async rewrites() {
return [
{
source: "/_fah/image/:path*",
destination:
"<CLOUD_FUNCTIONS_URL>/:path*",
},
];
},
}
module.exports = nextConfig;
然后在根目录中创建一个 loader.js
文件,其中包含以下内容:
"use client"
export default function myImageLoader({ src, width, quality }) {
if (process.env.NODE_ENV === "development") {
return src;
}
const operations = [
{
operation: "input",
type: "url",
url: src,
},
{ operation: "resize", width: width },
{ operation: "output", format: "webp", quality: quality || 75 },
];
const encodedOperations = encodeURIComponent(JSON.stringify(operations));
return `/_fah/image/process?operations=${encodedOperations}`;
}
创建一个包含这些更改的提交,并将其推送到您的正式版分支。
然后,等待 App Hosting 发布完成。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-29。
[null,null,["最后更新时间 (UTC):2025-08-29。"],[],[],null,["\u003cbr /\u003e\n\nBy default, built-in [Next.js image\noptimization](https://nextjs.org/docs/app/building-your-application/optimizing/images)\nis disabled on App Hosting unless you explicitly set\n[`images.unoptimized`](https://nextjs.org/docs/pages/api-reference/components/image#unoptimized)\nto false or use a custom [Image\nLoader.](https://nextjs.org/docs/app/api-reference/config/next-config-js/images#example-loader-configuration)\n\nYou can configure a Next.js global image loader with the Image Processing\nFirebase Extension to enable on-demand optimization and delivery of images in\nyour Next.js app on App Hosting.\n\nPrerequisites\n\n- You have a Firebase project and an App Hosting backend.\n- Cloud Storage is enabled in your project.\n- Cloud Functions for Firebase is enabled in your project.\n\nInstall the extension\n\nNavigate to the [Image Processing\nExtension](https://extensions.dev/extensions/invertase/image-processing-api) in\nthe Firebase Extensions Hub and select **Install in Firebase Console**. Follow\nthe on-screen instructions.\n\nConfigure [local image](https://nextjs.org/docs/pages/building-your-application/optimizing/images#local-images) optimization (optional)\n\nIf your application uses local images that you want to optimize using this\nextension, you need to configure the \"Hostname\" parameter during the extension\ninstallation process.\n\n1. **During Extension Configuration:** When you reach the \"Configure extension\"\n step, locate the \"Hostname\" parameter.\n\n2. **Set the Hostname:** Enter the default domain for your Firebase App Hosting\n backend. This domain typically ends with `.hosted.app`.\n\nOnce installation is complete, the Image Processing API should be deployed as a\nfunction in Cloud Functions. Navigate to the [Functions\ndashboard](https://console.firebase.google.com/project/_/functions) in the\nFirebase console and copy the Image Processing API trigger URL.\n\nSet up a custom image loader\n\nCreate an [image\nloader](https://nextjs.org/docs/app/api-reference/components/image#loaderfile)\nthat uses the deployed Image Processing API for every optimized [image\ncomponent](https://nextjs.org/docs/pages/api-reference/components/image). As an\noptimization,\n[rewrite](https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites)\nto it so that it's served under the same Firebase App Hosting domain and cached\nbehind the same global CDN as your Next.js application.\n\nFirst, add the following fields to your\n[`next.config.js`](https://nextjs.org/docs/app/api-reference/config/next-config-js)\nfile: \n\n // @ts-check\n\n /** @type {import('next').NextConfig} */\n const nextConfig = {\n images: {\n loader: \"custom\",\n loaderFile: \"./loader.js\",\n },\n async rewrites() {\n return [\n {\n source: \"/_fah/image/:path*\",\n destination:\n \"\u003cCLOUD_FUNCTIONS_URL\u003e/:path*\",\n },\n ];\n },\n }\n\n module.exports = nextConfig;\n\nThen create a `loader.js` file in your root directory with the following\ncontents: \n\n \"use client\"\n\n export default function myImageLoader({ src, width, quality }) {\n if (process.env.NODE_ENV === \"development\") {\n return src;\n }\n\n const operations = [\n {\n operation: \"input\",\n type: \"url\",\n url: src,\n },\n { operation: \"resize\", width: width },\n { operation: \"output\", format: \"webp\", quality: quality || 75 },\n ];\n\n const encodedOperations = encodeURIComponent(JSON.stringify(operations));\n\n return `/_fah/image/process?operations=${encodedOperations}`;\n }\n\nCreate a commit that includes these changes and push it to your live branch.\nThen, wait for the App Hosting rollout to complete."]]