Next.js添加网页图片报错:域名未配置,求助解决方法
解决Next.js next/image加载外部图片报错问题
核心问题分析
你当前的配置存在两个关键错误:
domains配置里用了中文“和”,属于语法错误,导致配置不生效- 尝试
remotePatterns时,pathname写的/account123/**和目标图片的路径不匹配,无法命中规则
正确配置方案
根据你的需求,提供两种有效配置方式:
方式一:使用domains(简单场景适用)
修改next.config.js为以下内容,确保域名数组格式正确:
/** @type {import('next').NextConfig} */ const nextConfig = { images: { domains: ["www.coloplast.com", "coloplast.com"], }, }; module.exports = nextConfig;
方式二:使用remotePatterns(Next.js 12.3+推荐,更安全)
如果需要更精确的路径匹配,用这种方式,注意pathname要和图片实际路径匹配:
/** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { protocol: "https", hostname: "www.coloplast.com", pathname: "/**", // 匹配该域名下所有图片,也可以写更精确的路径如"/Global/1_Corporate_website/Press/Pics/**" }, { protocol: "https", hostname: "coloplast.com", pathname: "/**", }, ], }, }; module.exports = nextConfig;
必做操作
修改完配置后,必须完全停止开发服务器,再重新启动,热重载不会加载新的配置。
测试代码示例
配置生效后,用next/image组件加载图片的示例:
import Image from 'next/image'; export default function YourPage() { return ( <Image src="https://www.coloplast.com/Global/1_Corporate_website/Press/Pics/CPlogo_Gray_RGB_300.png" alt="Coloplast Logo" width={300} height={100} /> ); }
内容的提问来源于stack exchange,提问作者AleshaLearner
相关产品推荐
相关产品推荐

