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 构建高性能的网站。