I’ve been doing some research on the preview functionality in Gatsby as well, and I’m currently stuck.
I think I’ve found a way to make it work.
A common reason for why previews break, is because Prismic does not support the gatsby-transformer-sharp
plugin. And they don’t seem to plan on doing so anytime soon.
However, there’s a work around.
We can conditionally include parts of a graphql query in gatsby, by using a directive.
That means we can utilize the gatsby-node.js
lifecycle hook onCreatePage
to introduce a context variable, that indicates whether or not the build is production or not. We can then use an environment variable to include or exclude the imageSharp
-part of our queries.
.env.production (or in your CI)
GATSBY_ACTIVE_ENV=production
gatsby-node.js
exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions
if (typeof page.context.isProduction === 'undefined') {
const newPage = {
...page,
context: {
...page.context,
isProduction: process.env.GATSBY_ACTIVE_ENV === "production", // allows for reviews
},
}
deletePage(page)
createPage(newPage)
}
}
src/templates/page.jsx
import React from 'react'
import { graphql } from 'gatsby'
function Page({ data: { prismic: { page } }, ...props }) {
if (!page) return null // Needed for preview pages not to break
return (
<Layout>
<Content content={page.page_title} />
<Content content={page.content} />
{page.imageSharp ? (
<Img fixed={page.imageSharp.childImageSharp.main} />
) : (
<img src={page.image.url} alt={page.image.alt} />
)}
</Layout>
)
}
export const query = graphql`
query PageQuery($lang: String!, $uid: String!, $isProduction: Boolean!) {
prismic {
page(lang: $lang, uid: $uid) {
content
page_title
image
imageSharp @include(if: $isProduction) {
childImageSharp {
id
main: fixed(width: 1200) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
`
However, this does not work as the query is invalid on Prismics graphql endpoint. It does not allow custom variables such as isProduction
.
I have made a small repository that reproduces the issue here: https://github.com/MadsMadsDk/prismic-preview-i18n-gatsby-test