A Gatsby plugin for fetching source data from the Prismic headless CMS using Prismic's beta GraphQL API. This plugin provides full support for Prismic's preview feature out of the box.
For more context, be sure to checkout Prismic's getting started guide: Using Prismic With Gatsby. This README, however, serves as the most-up-to-date source of information on gatsby-source-prismic-graphql's latest developments and breaking changes.
Please be sure your Prismic repository has the GraphQL API enabled. It is enabled by default on all new Prismic repositories. If you have an older repository or are unable to access https://[your_repo].prismic.io/graphql, please reach out to Prismic support to request the GraphQL API.
gatsby-source-prismic-graphql (this plugin) fetches data using Prismic's beta GraphQL API and provides full support for Prismic's Preview feature out of the box. It also provides an easy-to-configure interface for page generation.
gatsby-source-prismic is a different plugin that fetches data using Prismic's REST and Javascript APIs. Previews must be coded up separately.
Getting Started
Install the plugin
npm install --save gatsby-source-prismic-graphql
or
yarn add gatsby-source-prismic-graphql
Add plugin to gatsby-config.js and configure
{resolve: 'gatsby-source-prismic-graphql',options: {repositoryName: 'gatsby-source-prismic-test-site',// requireddefaultLang: 'en-us',// optional, but recommendedaccessToken: '...',// optionalprismicRef: '...',// optional, default: master; useful for A/B experimentspath: '/preview',// optional, default: /previewpreviews: true,// optional, default: truepages: [{// optionaltype: 'Article',// TypeName from prismicmatch: '/article/:uid',// pages will be generated under this patternpreviewPath: '/article',// optional path for unpublished documentscomponent: require.resolve('./src/templates/article.js'),sortBy: 'date_ASC',// optional, default: meta_lastPublicationDate_ASC; useful for pagination}],extraPageFields: 'article_type',// optional, extends pages query to pass extra fieldssharpKeys: [/image|photo|picture/,// (default)'profilepic',],}}
Given 3 articles with UIDs of why-i-like-music, why-i-like-sports and why-i-like-food, the following URL slugs will be generated:
/musicblog/why-i-like-music
/blog/why-i-like-sports
/blog/why-i-like-food
Generating pages from page fields
Sometimes the meta provided by default doesn't contain enough context to be able to filter pages effectively. By passing extraPageFields to the plugin options, we can extend what we can filter on.
Given 2 articles with the music_genre field set, we'll get the following slugs:
/techno/darude
/acoustic/mik-parsons
Support for Multiple Languages
Prismic allows you to create your content in multiple languages. This library supports that too. When setting up your configuration options in gatsby-config.js, there are three optional properties you should be aware of: options.defaultLang, options.langs, and options.pages[i].langs. In the following example, all are in use:
In the example above, pages are generated for two document types from Prismic--Articles and Noticias. The latter consists of news stories in Spanish. There are three languages total in use in this blog: US English, Traditional Spanish and Icelandic.
For Articles, we are instructing the plugin to generate pages for articles of all three languages. But, because there is a question mark (?) after the :lang portion of the match property (/:lang?/:uid), we only include the locale tag in the URL slug for languages that are not the defaultLang specified above (i.e., 'en-us'). So for the following languages, these are the slugs generated:
US English: /epic-destinations
Spanish: /es-es/destinos-increibles
Icelandic: /is/reykjadalur
If we had not specified a defaultLang, the slug for US English would have been /en-us/epic-destinations. And, in fact, including the langs: ['en-us', 'es-es', 'is'] declaration for this particular document type (Articles) is unnecessary because we already specified that as the default language set right after defaultLang in the plugin options.
For Noticias, however, we only want to generate pages for Spanish documents of that type (langs is [es-es]). We decide that in this context, no locale tag is needed in the URL slug; "noticias" is already enough indication that the contents are in Spanish. So we omit the :lang match entirely and specify only match: '/noticias/:uid'.
This is an example of how these three properties can be used together to offer maximum flexibility. To see this in action, check out the languages example app.
(Optional) Short language codes
To use short language codes (e.g. /fr/articles) instead of the default (e.g. /fr-fr/articles), you can set options.shortenUrlLangs to true.
Keep in mind that if you use this option & have multiple variants of a language (e.g. en-us and en-au) that would be shortened to the same value, you should add UIDs to your URLs to differentiate them.
Page Queries: Fetch Data From Prismic
It is very easy to fetch data from Prismic in your pages:
importReactfrom'react';import{RichText}from'prismic-reactjs';exportconstquery=graphql` { prismic { page(uid:"homepage", lang:"en-us") { title description } } }`exportdefaultfunctionPage({ data })=><><h1>{RichText.render(data.prismic.title)}</h1><h2>{RichText.render(data.prismic.description)}</h2></>
Prismic Previews
Previews are enabled by default, however they must be configured in your prismic instance/repository. For instructions on configuring previews in Prismic, refer to Prismic's guide: How to set up a preview.
When testing previews, be sure you are starting from a valid Prismic preview URL/path. The most reliable way to test previews is by using the preview button from your draft in Prismic. If you wish to test the Preview locally, catch the URL that opens immediately after clicking the preview link:
import{graphql}from'gatsby';constfragmentX=graphql` fragment X on Y { ... } `;exportconstquery=graphql` query { ...X }`;constMyPage=(data)=>{ ... };MyPage.fragments=[fragmentX];exportdefaultMyPage;
With StaticQuery:
import{StaticQuery,graphql}from'gatsby';import{withPreview}from'gatsby-source-prismic-graphql';constfragmentX=graphql` fragment X on Y { ... } `;exportconstquery=graphql` query { ...X }`;exportdefault()=>(<StaticQueryquery={query}render={withPreview(data=>{ ... },query,[fragmentX])}/>);
Dynamic Queries and Fetching
You can use this plugin to dynamically fetch data for your component using prismic.load. Refer to the pagination example to see it in action.
Pagination can be accomplished statically (i.e., during initialy page generation) or dynamically (i.e., with JS in the browser). Examples of both can be found in the pagination example.
Prismic pagination is cursor-based. See Prismic's Paginate your results article to learn about cursor-based pagination.
By default, pagination will be sorted by last publication date. If you would like to change that, specify a sortBy value in your page configuration in gatsby-config.js.
Dynamically-Generated Pagination
When coupled with prismic.load, as demonstrated in the index page of the pagination example, other pages can be fetched dynamically using page and cursor calculations.
GraphQL documents from Prismic have a cursor--a base64-encoded string that represents their order, or page number, in the set of all documents queried. We provide two helpers for converting between cursor strings and page numbers:
getCursorFromDocumentIndex(index: number)
getDocumentIndexFromCursor(cursor: string)
Statically-Generated Pagination
Basic Pagination
For basic linking between the pages, metadata for the previous and next pages are provided to you automatically via pageContext in the paginationPreviousMeta and paginationNextMeta properties. These can be used in conjunction with your linkResolver to generate links between pages without any additional GraphQL query. For an example of this, take a look at the <Pagination /> component in the pagination example's article.js.
Enhanced Pagination
If you would like to gather other information about previous and next pages (say a title or image), simply modify your page query to retrieve those documents. This also is demonstrated in the same pagination example with the <EnhancedPagination /> component and the page's GraphQL query.
Working with gatsby-image
The latest versions of this plugin support gatsby-image by adding a new property to GraphQL types that contains fields that match the sharpKeys array (this defaults to /image|photo|picture/) to the Sharp suffix.
Note: When querying, make sure to also query the source field. For example:
Later, we may add an Image component that does this for you and leverages the new Prismic Image API as a fallback for preview modes.
Prismic.io Content A/B Experiments Integration
You can use this plugin in combination with Prismic's built-in experiments functionality, and a hosting service like Netlify, to run content A/B tests.
Experiments in Prismic are basically branches of the core content, split into 'refs' similar to git branches. So if you want to get content from a certain experiment variation, you can pass the corresponding ref through to Prismic in your request, and it will return content based on that ref's variation.
A/B experiments are tricky to implement in a static website though; A/B testing needs a way to dynamically serve up the different variations to different website visitors. This is at odds with the idea of a static, non-dynamic website.
Fortunately, static hosting providers like Netlify allow you to run A/B tests at a routing level. This makes it possible for us to build multiple version
请发表评论