Gatsby logo

Store Gatsby GraphQL fragments in their own external files

No more jamming everything in your Layout component.
  • by Zach (170)
  • Time to complete: 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!

1

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

src/graphql-fragments
2

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.

3

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!