配置Next.js remotePatterns后加载外部图片仍带_next/image前缀,如何绕过?
解决Next.js Image组件自动添加/_next/image前缀的问题
要绕过Next.js Image组件自动给图片URL添加/_next/image前缀的行为,有两种可行方案,且都不需要改用原生img标签:
1. 全局禁用图片优化
直接在next.config.js中添加unoptimized: true配置,全局关闭Next.js的图片优化代理:
const nextConfig = { images: { remotePatterns: [ { protocol: "http", hostname: "api.example.app", port: "" } ], // 开启该配置后,Image组件将直接使用原始图片URL unoptimized: true } }
2. 单个组件单独设置
如果不想全局禁用图片优化,也可以在需要的Image组件上单独添加unoptimized属性:
import Image from 'next/image' export default function YourComponent() { return ( <Image src="http://api.example.app/assets/photo.png" alt="自定义图片" width={600} height={400} // 仅当前组件跳过Next.js的图片代理 unoptimized={true} /> ) }
⚠️ 注意:开启unoptimized后,Next.js会停止对图片进行格式转换、自适应尺寸生成等优化操作,这些工作需要由你的后端服务(api.example.app)自行处理。
内容的提问来源于stack exchange,提问作者Mammad Mammadli
相关产品推荐
相关产品推荐

