Store Gatsby GraphQL Fragments in Their Own External Files

No more jamming everything in your Layout component.
Zach Zach (248)
2 minutes

Did you know that you can store your Gatsby GraphQL fragments in their own files rather than defining them all in some top-level component? Until recently, neither did I.

In order for a GraphQL fragment to be accessible by Gatsby pages, templates, and components, it generally needs to live in some parent or wrapper component. Usually, this is something like your site's PageWrapper.jsx or Layout.jsx component.

The problem

In practice, this leads to a large collection of fragments in that file, where a single syntax error can cause your gatsby develop to fail and require a restart. Not only is this extremely annoying, but a growing list of fragments means a larger and more unwieldy wrapper component.

The solution

Instead, it's a good idea to store each fragment in its own file instead. This is not a well-documented Gatsby feature, so thanks to howchooer Ryan for pointing this out to me!

tl;dr;

You can define SomeFragment in src/graphql-fragments/SomeFragment.js!

Posted in these interests:
Gatsby
h/gatsby2 guides
React
h/react3 guides
h/graphql1 guide

You'll need to create a particular folder structure for Gatsby to detect and use your fragments. Create the following directory:

src/graphql-fragments

Create a file with a name matching your fragment. For example, create src/graphql-fragments/SomeFragment.js and populate it with your fragment:

import { graphql } from 'gatsby';

export const SomeFragment = graphql`
    fragment SomeFragment on SomeTypeName {
        id
    }
`;

That's it! Gatsby will automatically detect these fragments and make them available for use.

Restarting develop

If you're moving existing fragments, it's possible Gatsby will puke as a result of undefined or duplicate fragments. In this case, simply restart develop by running npm start or gatsby develop.

Continue to reference and use your fragments like normal:

...
edges {
    node {
        ...SomeFragment
    }
}
...

Now you can keep your project nice and clean while reducing the develop restarts normally associated with GraphQL fragment syntax errors!

Hint: you technically aren't looking to save but to export.
Michael Michael (175)
0

In just about every application in the Adobe software suite, they've built their own file types when you save. In InDesign, the default file type you can save as is .