How to create & use backend GraphQL fragments in Gatsby
A step by step tutorial on creating and using reusable GraphQL fragments for a GatsbyJS backend.
The following tutorial builds off our Open Source starter project and walks you through how to create and use reusable GraphQL fragments that can be used as part of the createPages, or other gatsby-node functionality, in GatsbyJS.
We recommend downloading our Open Source project, checking out the tutorial/page-queries-with-variables branch and carrying out the steps outlined below. All relevant changes can be found on the tutorial/backend-fragments branch.
git clone git@github.com:delasign/gatsbyjs-typescript-starter.git<a href="https://github.com/delasign/gatsbyjs-typescript-starter.git"></a>
Step One: Create the fragment
In our case, we will be creating a fragment called base which will include the slug and uri that we used as part of our tutorial on creating pages programatically.
In the graphql folder at the root directory, create a new folder called fragments and within it create a new file called base.js and paste in the code found below.
Step Two: Import & Consume
In graphl/post.js import the fragment that was created in Step One and add it to your query as demonstrated in the code below.
Step Three: Verify
Run yarn start to confirm that the page generation algorithm succeeds.
Once complete, navigate to a webpage generated by Gatsby to see your results.
Any Questions ?
We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.