Gatsby Source Sanity 插件使用指南

Gatsby Source Sanity 插件使用指南

gatsby-source-sanityGatsby source plugin for building websites using Sanity.io as a backend.项目地址:https://gitcode.com/gh_mirrors/ga/gatsby-source-sanity

项目介绍

gatsby-source-sanity 是一个 Gatsby 源插件,用于将数据从 Sanity.io 拉取到 Gatsby 网站中。Sanity.io 是一个托管的结构化内容后端,带有用 React 构建的开源编辑器。该插件支持实时预览所有内容更改,并与 gatsby-plugin-image 兼容。它使用项目的 GraphQL 模式定义来避免意外的缺失字段,无需使用虚拟内容。

项目快速启动

安装

首先,确保你已经有一个 Gatsby 项目。如果没有,可以使用以下命令创建一个新项目:

gatsby new my-sanity-gatsby-site
cd my-sanity-gatsby-site

然后,安装 gatsby-source-sanity 插件:

npm install gatsby-source-sanity

配置

gatsby-config.js 文件中添加插件配置:

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: 'your-project-id',
        dataset: 'your-dataset-name',
        token: process.env.SANITY_TOKEN, // 可选,用于私有数据集
        graphqlTag: 'default' // 可选,指定 GraphQL API 标签
      }
    }
  ]
}

运行

启动 Gatsby 开发服务器:

gatsby develop

访问 http://localhost:8000 查看你的网站,并使用 http://localhost:8000/___graphql 进行 GraphQL 查询。

应用案例和最佳实践

使用图像

使用 gatsby-plugin-image 处理 Sanity 中的图像:

import { getGatsbyImageData } from 'gatsby-source-sanity'

const sanityConfig = { projectId: 'your-project-id', dataset: 'your-dataset-name' }
const imageAssetId = 'image-488e172a7283400a57e57ffa5762ac3bd837b2ee-4240x2832-jpg'
const imageData = getGatsbyImageData(imageAssetId, { maxWidth: 1024 }, sanityConfig)

<GatsbyImage image={imageData} />

生成页面

gatsby-node.js 中创建页面:

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const result = await graphql(`
    query {
      allSanityPost {
        edges {
          node {
            id
            slug {
              current
            }
          }
        }
      }
    }
  `)

  result.data.allSanityPost.edges.forEach(({ node }) => {
    createPage({
      path: node.slug.current,
      component: path.resolve('./src/templates/blog-post.js'),
      context: {
        id: node.id
      }
    })
  })
}

典型生态项目

gatsby-plugin-image

gatsby-plugin-image 是一个 Gatsby 插件,用于优化和处理图像。它与 gatsby-source-sanity 结合使用,可以提供高性能的图像加载体验。

Sanity.io

Sanity.io 是一个 headless CMS,提供强大的实时 API 用于读写数据。它允许作者在一个用户友好的环境中工作,或者作为应用程序的纯数据后端。

通过以上步骤,你可以快速启动并使用 gatsby-source-sanity 插件,结合 Sanity.io 和 Gatsby 构建高性能的网站。

gatsby-source-sanityGatsby source plugin for building websites using Sanity.io as a backend.项目地址:https://gitcode.com/gh_mirrors/ga/gatsby-source-sanity

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邱晋力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值