Next.js 13中使用Sanity展示图片报错:urlFor不是函数
解决Next.js 13 + Sanity图片展示报错:
urlFor is not a function 问题根源
报错核心是导入方式不匹配:Shared/Image.js默认导出urlFor函数,但Solution.jsx用了命名导入,导致无法正确获取该函数;同时需确认Sanity配置文件的导入路径是否正确。
修复步骤
1. 修正Solution.jsx的导入语句
将命名导入改为默认导入:
// 错误写法 // import {urlFor} from '../shared/Image' // 正确写法 import urlFor from '../shared/Image'
2. 检查Shared/Image.js的配置文件路径
确保sanity.config的导入路径匹配项目结构,比如sanity.config在根目录时,路径应为../sanity.config:
// Shared/Image.js 'use client' import imageUrlBuilder from '@sanity/image-url' // 按项目实际结构调整路径 import sanityConfig from '../sanity.config' const builder = imageUrlBuilder(sanityConfig) function urlFor(source) { return builder.image(source) } export default urlFor
3. 验证Sanity配置正确性
确认sanity.config里的projectId和dataset与你的Sanity项目一致:
// sanity.config.js export default defineConfig({ name: 'default', title: 'Sanity Project', projectId: 'q8l0xi0c', // 确保是你的项目ID dataset: 'production', // 确保是正确的数据集 plugins: [deskTool(), visionTool()] })
4. 确认Next.js图片域名配置
检查next.config.js已正确配置Sanity CDN域名,允许Next.js加载该域名图片:
// next.config.js images: { remotePatterns: [ { protocol: 'https', hostname: 'cdn.sanity.io', }, ], },
完成以上步骤后重启项目,图片即可正常加载。
内容的提问来源于stack exchange,提问作者samira rahimi
相关产品推荐
相关产品推荐

