You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已配置Gatsby-Contentful双插件,如何搭建预览页面?

实现Gatsby + Contentful预览页面的完整步骤

你已经正确配置了Contentful的Delivery和Preview两个数据源,接下来我们一步步完成预览功能的搭建:

1. 给数据源添加标识(区分预览/生产内容)

首先修改你的gatsby-config.js,给两个gatsby-source-contentful插件添加name字段,这样后续查询时能明确区分来自预览API还是生产API的内容:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: `space-id`,
        accessToken: `preview-access-token`,
        host: `preview.contentful.com`,
        name: `preview` // 给预览源加标识
      }
    },
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: `space-id`,
        accessToken: `delivery-access-token`,
        name: `delivery` // 给生产源加标识
      }
    }
  ]
}

2. 创建预览页面模板

在src/pages/preview/[slug].js路径下创建动态预览页面,这个页面专门用于展示Contentful的草稿内容:

import React from "react"
import { graphql } from "gatsby"
import { renderRichText } from "gatsby-source-contentful/rich-text"

export default function PreviewBlogPost({ data }) {
  const post = data.contentfulBlogPost
  if (!post) {
    return <div>Loading preview content...</div>
  }

  return (
    <div className="blog-post-preview">
      <h1>{post.title}</h1>
      {renderRichText(post.body)}
      {/* 这里复制你生产页面的渲染逻辑,保证预览效果和生产一致 */}
    </div>
  )
}

// 查询预览源中的博客内容,通过slug匹配
export const query = graphql`
  query PreviewBlogPostQuery($slug: String!) {
    contentfulBlogPost(
      slug: { eq: $slug }
      sourceInstanceName: { eq: "preview" }
    ) {
      title
      body {
        raw
      }
      slug
      # 添加你需要的其他字段,和生产页面保持一致
    }
  }
`

注意:要确保预览页面的渲染逻辑和你的生产博客页面完全一致,这样才能准确预览最终效果

3. 配置Contentful后台的预览URL

现在需要让Contentful知道点击“Open Preview”时要跳转的地址:

  1. 登录Contentful后台,进入你的Space
  2. 点击顶部导航的Settings → Preview
  3. 在Preview URLs区域,找到你的博客内容类型(比如Blog Post),设置预览URL:
    • 如果是本地开发:http://localhost:8000/preview/{entry.fields.slug}
    • 如果是线上预览环境:https://your-preview-domain.com/preview/{entry.fields.slug}
  4. 保存设置

4. 测试预览功能

  • 本地开发时,启动Gatsby开发服务器:gatsby develop
  • 进入Contentful的内容编辑界面,打开一篇草稿文章(或修改已发布文章并暂存为草稿)
  • 点击右上角的“Open Preview”按钮,会自动跳转到你的Gatsby预览页面,此时就能看到未发布的草稿内容了

额外优化建议

  • 环境变量隔离:为了避免生产构建时拉取预览内容,建议用环境变量控制数据源的启用,比如在生产环境只加载delivery源,预览环境只加载preview源
  • 预览权限控制:如果是线上预览页面,建议添加简单的身份验证(比如密码),防止未授权用户访问草稿内容
  • 实时预览更新:如果需要在Contentful编辑时实时同步预览页面,可以结合Gatsby的实时刷新功能,提升编辑体验

内容的提问来源于stack exchange,提问作者Yegeon Seo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:16:14