Gatsby对接Contentful时GraphQL无法查询fluid图片字段如何修复
问题根因
fluid字段查询失效是Gatsby版本迭代带来的破坏性变更导致的,和是否安装gatsby-image、是否正确导入组件没有关系:
- Gatsby v3及以上版本中,旧版
gatsby-image配套的图片处理逻辑被重构,v4.0+版本的gatsby-source-contentful直接移除了原有的fluid、fixed字段,改为适配新版图片体系的gatsbyImageData字段 - 代码中使用的
...GatsbyContentfulFluidGraphQL片段,仅在旧版v2生态的gatsby-plugin-sharp、gatsby-transformer-sharp、gatsby-source-contentful组合下才会被自动注册,版本错配时GraphQL Playground不会识别该字段。
修复方案
根据当前使用的Gatsby主版本二选一即可:
方案1:最小改动兼容旧代码(仅适用于Gatsby v2/v3)
如果不想重构现有组件代码,直接将相关依赖锁定到兼容旧版fluid字段的版本:
npm install gatsby-source-contentful@2.3.50 gatsby-plugin-sharp@2.14.4 gatsby-transformer-sharp@2.12.1
安装完成后清空缓存重启开发服务:
gatsby clean && gatsby develop
重启后即可正常查询fluid字段,原有组件逻辑无需调整。
方案2:适配新版Gatsby图片体系(官方推荐,兼容Gatsby v3+全版本)
替换旧版gatsby-image为官方维护的新版gatsby-plugin-image,长期兼容性更好,对GIF动图的支持也更完善,不会出现动图被压缩为静态首帧的问题:
- 安装新版依赖
npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-contentful@latest
- 在项目根目录的
gatsby-config.js中注册插件:
module.exports = { plugins: [ // 保留原有其他插件配置 `gatsby-plugin-image`, `gatsby-plugin-sharp`, { resolve: `gatsby-source-contentful`, options: { spaceId: `个人Contentful空间ID`, accessToken: `个人Contentful访问令牌`, }, }, ] }
- 调整组件代码:替换导入的图片组件,修改GraphQL查询字段,修正原代码中React不支持的
class属性为className,修改后完整代码如下:
import React from "react" import { Link, useStaticQuery, graphql } from "gatsby" import { GatsbyImage, getImage } from "gatsby-plugin-image" import projectStyles from "../styles/projects.module.scss" const Project = () => { const data = useStaticQuery(graphql` query { allContentfulProject(sort: { fields: publishedDate, order: DESC } ) { edges { node { title slug logline stackList publishedDate (formatString:"YYYY") code liveLink image { title gatsbyImageData( width: 450 layout: CONSTRAINED placeholder: BLURRED formats: [AUTO, WEBP] ) } } } } } `) return ( <section> <ol className={projectStyles.posts}> {data.allContentfulProject.edges.map((edge) => { const projectImage = getImage(edge.node.image) return ( <li className={projectStyles.post}> <div className={projectStyles.previewImage}> <GatsbyImage image={projectImage} alt={edge.node.image.title} /> </div> <div className={projectStyles.info}> <p>{edge.node.publishedDate}</p> <div className={projectStyles.headline}> <h2>{edge.node.title}: <h3>{edge.node.logline}</h3></h2> </div> <p>{edge.node.stackList}</p> <div className={projectStyles.buttons}> <Link to={`${edge.node.code}`} className={projectStyles.button}>Code</Link> <div className={projectStyles.divider}></div> <Link to={`${edge.node.liveLink}`} className={projectStyles.button}>Live</Link> </div> </div> </li> ) })} </ol> </section> ) } export default Project
- 清空缓存重启服务即可生效:
gatsby clean && gatsby develop
内容的提问来源于stack exchange,提问作者kenton
相关产品推荐
相关产品推荐

