GraphQL Code Generator for WPGraphQL

Kellen Mace Avatar

·

When getting started with TypeScript, developers quickly become accustomed to defining their typings. For a React component that’s responsible for rendering a single blog post’s content, you may write something like this:

type Avatar = {
  url: string;
};

type User = {
  name: string;
  avatar: Avatar;
};

type Post = {
  databaseId: number;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  author: {
    node: User;
  }
};

type Props = {
  post: Post;
};

export default function BlogPost(props: Props) {
  const { post } = props;
  return (
    <article>
      <h1>{post.title}</h1>
      {/* etc. */}
    </article>
  );
}
Code language: JavaScript (javascript)

You can see that the BlogPost component accepts an argument with a type of Props, which itself uses a type of Post. Post uses the User type, which in turn uses the Avatar type. Sure, you may be able to nest some of those types inside others to make things a bit more concise, but you still end up with quite a few type definitions. While this code works fine, you may find that it is time-consuming to create all the types for your project manually.

If your project sources its data from a GraphQL API, you may look at the GraphQL schema and think:

“Wait…since my GraphQL schema is strongly typed, can’t I just leverage those same types in my TypeScript code instead of reinventing the wheel?”

You, my astute friend, are in luck! That is indeed possible using GraphQL Code Generator, a.k.a. “GraphQL Codegen.” This free, open-source tool can use your GraphQL schema to generate TypeScript typings. This image sums it up nicely:

Set Up

Let’s learn how you set up GraphQL Codegen in your headless WordPress projects that use WPGraphQL.

Enable GraphQL Introspection

In the WordPress admin sidebar of your local environment, head to GraphQL > Settings. Make sure the Enable Public Introspection option is checked. This will allow GraphQL Code Generator to run an introspection query against your GraphQL endpoint to get the entire schema.

Initialize GraphQL Code Generator

  1. Head over to the GraphQL Code Generator Getting Started documentation page. Follow the steps for installing the graphql and @graphql-codegen/cli NPM packages.
  2. Run npx graphql-codegen init (or yarn graphql-codegen init) to launch the initialization wizard. Below, we’ll cover what to enter for each prompt.

What type of application are you building?

Select Angular/React/any thing your heart desires.

Where is your schema?

Paste in your local WordPress site’s GraphQL endpoint. You can see it on the WPGraphQL settings page here:

Where are your operations and fragments?

Enter the path to where the .graphql files containing operations and fragments. Example: src/**/*.graphql. If you don’t have .graphql files in your project, just hit enter to go to the next step.

Pick plugins

Make sure to check TypeScript (required by other typescript plugins. Look if TypeScript Operations (operations and fragments) only if you have .graphql files containing GraphQL operations and fragments in your project; un-check it, if not. Leave all other options unchecked and hit enter to continue.

Where to write the output

Enter generated/graphql.ts. This tells GraphQL Code Generator what file it should write the generated typings.

Do you want to generate an introspection file?

Choose “No”.

How to name the config file?

Hit enter to accept the default codegen.yml filename.

What script in package.json should run the codegen?

Enter generate.

The GraphQL Codegen CLI will:

  • Generate a codegen.yml configuration file based on your answers
  • Add a few NPM packages to your devDependencies to your project
  • Add a new generate script in package.json. You’ll be able to run whenever you want to generate your typings

The command line output should look something like this:

Next, run npm install (or yarn) to install the new devDependencies.

If you do not have .graphql files containing GraphQL operations and fragments in your project, remove the entire documents: line from codegen.yml and save the file. If you don’t do this, GraphQL Codegen will throw an error when you try to generate your typings since it will be unable to find those files.

Generate Your Typings

With typing set up complete , run npm run generate to generate your typings. GraphQL Code Generator will access the GraphQL schema via your local site’s GraphQL endpoint and generate TypeScript typings.

Congrats! You have now used your GraphQL schema to generate TypeScript typings you can use in your frontend app! You can check out the generated/graphql.ts file to see all the generated typings.

How to Use the Generated Types

Let’s revisit our BlogPost component example from the beginning of this blog post. Rather than all of those type definitions we had created manually, we can instead do this:

import { Post } from "../../generated/graphql";

type Props = {
  post: Post;
};

export default function BlogPost(props: Props) {
  const { post } = props;
  return (
    <article>
      <h1>{post.title}</h1>
      {/* etc. */}
    </article>
  );
}
Code language: JavaScript (javascript)

You can see that this is quite a bit simpler. Rather than creating our typings manually, we can leverage the ones that GraphQL Codegen generated for us.

When to Generate Typings

You can commit the generated/graphql.ts to your version control system so the generated types are stored alongside the rest of your project. Anytime you want to regenerate the types (such as if you make changes to the GraphQL schema or install a WPGraphQL extension), you can run npm run generate again. This will overwrite your current generated/graphql.ts file.

Plugins & Integrations

We’ve learned the basics of how to set up and run GraphQL Code Generator to generate typings using our GraphQL schema. If you want to go further and automatically generate even more code for your project, I encourage you to check out the GraphQL Code Generator plugins available.

There are plugins available for Apollo Client, React Query, GraphQL Request. and other popular libraries that generate other things for you, such as custom React hooks, higher-order components, etc.

Note for Gatsby users: an integration also exists to generate typings from Gatsby’s unified GraphQL data layer. See the documentation for details.

Wrapping Up

I hope this post is helps you understand the benefits you can gain by using GraphQL Code Generator to generate typings for your frontend JavaScript app based on your GraphQL schema. You should also have a good idea of how to set up GraphQL Codegen for your projects and run it to generate your types. Thanks for reading! ????