已配置域名,NextJS仍抛出next/image未配置主机名错误求助
NextJS next/image 已配置域名仍报错的排查方案
问题描述
已在NextJS配置文件中配置图片域名res.cloudinary.com,但next/image组件仍抛出未配置主机名错误,该功能此前运行正常,近期突然失效。
错误提示
Error: Invalid src prop (https://res.cloudinary.com/damilola-space/image/upload/c_fill,w_500,h_500,q_100,g_face,f_png/dump/IMG_1143_tgzqo2) on `next/image`, hostname "res.cloudinary.com" is not configured under images in your `next.config.js` See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host
当前配置文件
/** @type {import('next').NextConfig} */ const withOffline = require('next-pwa'); // eslint-disable-next-line import/no-extraneous-dependencies const withTM = require('next-transpile-modules')([ 'ui', 'utils', 'hooks', 'types', ]); const nextConfig = withTM(withOffline({ reactStrictMode: true, images: { domains: [ 'res.cloudinary.com', ], }, pwa: { dest: 'public', register: true, skipWaiting: true, publicExcludes: ['!images/**/*'], buildExcludes: [/image\/public\/images\/.*$/], }, })); module.exports = nextConfig;
解决步骤
- 重启开发服务器:NextJS修改配置后必须重启服务才能加载新配置,大概率是近期改完配置没重启导致的。
- 调整插件嵌套顺序:部分NextJS插件的嵌套逻辑会影响配置合并,把
withTM和withOffline的顺序调换试试:const nextConfig = withOffline(withTM({ reactStrictMode: true, images: { domains: ['res.cloudinary.com'], }, pwa: { dest: 'public', register: true, skipWaiting: true, publicExcludes: ['!images/**/*'], buildExcludes: [/image\/public\/images\/.*$/], }, })); - 验证配置是否生效:在配置文件末尾加一行
console.log(nextConfig.images),重启服务后看终端输出,确认domains里确实有res.cloudinary.com,排查是否有其他代码或插件覆盖了这个配置。 - 补充remotePatterns配置:如果是较新的NextJS版本,单独用
domains可能有兼容问题,加上remotePatterns试试:images: { domains: ['res.cloudinary.com'], remotePatterns: [ { protocol: 'https', hostname: 'res.cloudinary.com', }, ], } - 清除缓存:删掉项目根目录下的
.next文件夹,再重启服务,同时清空浏览器缓存,避免旧配置残留。
内容的提问来源于stack exchange,提问作者Damiisdandy
相关产品推荐
相关产品推荐

