部署至Firebase Hosting后next/image图片无法显示的求助
解决Next.js图片部署到Firebase Hosting不显示的问题
1. 配置Next.js静态导出参数
如果用next export生成静态资源,必须在next.config.js里做以下配置:
/** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', images: { unoptimized: true, // 静态导出模式下必须开启,否则Next.js图片优化逻辑会导致路径错误 }, assetPrefix: './', // 适配Firebase Hosting的相对路径规则 } module.exports = nextConfig;
注意:静态导出时无法使用Next.js的图片优化功能,开启
unoptimized后,图片会以原文件形式被打包。
2. 调整图片存放目录与引用方式
- 把图片移动到Next.js约定的
public目录下,比如public/Assets/car.jpg。 - 引用时直接使用根路径格式:
import Image from 'next/image'; <Image src="/Assets/car.jpg" alt="汽车" width={500} height={300} />
public目录下的资源会被自动打包到out目录,无需额外配置。
3. 检查Firebase Hosting配置
确保firebase.json里的托管目录指向out:
{ "hosting": { "public": "out", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "**", "destination": "/index.html" } ] } }
4. 验证打包结果再部署
执行npm run build后,查看out目录是否包含Assets文件夹及对应图片。确认无误后再执行firebase deploy。
5. 清理缓存重新部署
如果有缓存残留导致资源不更新,执行以下命令:
# 清理Next.js构建缓存 rm -rf .next out # 重新构建 npm run build # 强制部署Firebase Hosting firebase deploy --only hosting --force
内容的提问来源于stack exchange,提问作者Faleti Oluwaseyi Samuel
相关产品推荐
相关产品推荐

