npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

gatsby-plugin-graphql-codegen

v3.1.1

Published

Automate codegen for Gatsby via graphql-codegen

Downloads

24,371

Readme

Gatsby Typescript Graphql Codegen

Automatic type generation for your graphql queries via graphql-code-generator

Installation

yarn add typescript gatsby-plugin-graphql-codegen

Add this to your gatsby config like any other plugins:

// gatsby-config.js
module.exports = {
  plugins: [
    `gatsby-plugin-graphql-codegen`,
  ]
}

Options

|key | default | value | |---|---|---| |options.codegen| true | enable / disable generating definitions for graphql queries| |options.documentPaths| ['./src/**/*.{ts,tsx}','./.cache/fragments/*.js', './node_modules/gatsby-*/**/*.js'] | The paths to files containing graphql queries. ⚠️ The default paths will be overwritten by the documentPaths you pass in, so please make sure to include all necessary paths ⚠️ |options.fileName| graphql-type.ts | path to the generated file. By default, it's placed at the project root directory & it should not be placed into src, since this will create an infinite loop| |options.codegenDelay| 200 | amount of delay from file change to codegen| |options.pluckConfig| { globalGqlIdentifierName: "graphql", modules: [ { name: 'gatsby', identifier: 'graphql' } ] } | options passed to graphql-tag-pluck when extracting queries and fragments from documents | |options.failOnError (^2.5.0)| process.env.NODE_ENV === 'production' | Throw error if the codegen fails. By default only apply to production builds. |options.codegenConfig (^2.7.0)| {} | Add config directly to graphql-codegen. These key-value config will be applied to every graphql-codegen plugins. See graphql-codegen docs on the config field | |options.codegenPlugins (^2.7.0)| [] | Add additional plugins to graphql-codegen. We use the same format as Gatsby's. See example usage below. |options.additionalSchemas (^2.6.0)| [] | array of additional schemas (other than the schema used by gatsby queries) for which types should be generated for. This is useful when you use client-side queries (e.g. with apollo-client) where you are querying another schema/endpoint |

Additional Schema Options (for options.additionalSchemas)

|key | default | value | |---|---|---| |key| - | an unique key used internally by this plugin to identify different schemas| |fileName| graphql-types-${key}.ts | path to the generated file for this schema. By default, it's placed at the project root directory & it should not be placed into src, since this will create an infinite loop | |documentPaths| value of options.documentPaths | The paths to files containing graphql queries. See also options.documentPaths | |pluckConfig| - | options passed to graphql-tag-pluck when extracting queries and fragments from documents | |schema| - | additional schema to process. Can either be an url, a path to a local schema definition (both .json and .graphql are supported) or an inline definition. See also https://github.com/ardatan/graphql-toolkit#-schema-loading | |codegenConfig (^2.7.0)| {} | See codegenConfig above |codegenPlugin (^2.7.0)| {} | See codegenPlugin above

Example Setups

Normal Usecase

Set it & forget it

exports.default = {
  plugins: [
    `gatsby-plugin-graphql-codegen`,
  ]
}

Custom Filename & Location

exports.default = {
  plugins: [{
    resolve: `gatsby-plugin-graphql-codegen`,
    options: {
      fileName: `./gatsby-graphql.ts`,
    }
  }]
}

Gatsby-node.ts

You have queries in your gatsby-node? We can take care of that. The experience is not 100% right now, but that'll change soon!

exports.default = {
  plugins: [{
    resolve: `gatsby-plugin-graphql-codegen`,
    options: {
      fileName: `./gatsby-graphql.ts`,
      documentPaths: [
        './src/**/*.{ts,tsx}',
        './node_modules/gatsby-*/**/*.js',
        './gatsby-node.ts',
      ],
    }
  }]
}

Customize Graphql Codegen

You want to pass additional config to graphql-codegen:

// additional plugins
import { plugin as resolverPlugin } from '@graphql-codegen/typescript-resolvers'

exports.default = {
  plugins: [{
    resolve: `gatsby-plugin-graphql-codegen`,
    options: {
      codegenConfig: {
        // key-value configs that will be applied to every plugins.
        // Note: The example below is completely unnecessary, just a demonstration.
        typesPrefix: 'Hi' // -> import { HiImageQuery } from '../../graphql-types'
      },
      codegenPlugins: [{
        // built-in plugin. 
        // Use `typescript` for `@graphql-codegen/typescript`
        // and `operations` for `@graphql-codegen/typescript-operations`
        resolve: 'typescript',
        options: {
          namingConvention: `lower-case#lowerCase`,
        }
      },{
        // additional plugin
        resolve: resolverPlugin,
        options: {
          typesPrefix: 'I'
        }
      }]
    }
  }]
}

Dual-Schema Setup

If you use graphql on the client side, this is for you.

exports.default = {
  plugins: [{
    resolve: `gatsby-plugin-graphql-codegen`,
    options: {
      additionalSchemas: [{
        key: 'pokemon',
        fileName: './graphql-pokemon.ts',
        schema: 'https://graphql-pokemon.now.sh/',
        pluckConfig: {
          // config to ensure only queries using the `gql` tag are used for this schema
          globalGqlIdentifierName: 'gql',
          modules: [
            {
              name: 'graphql-tag',
              identifier: 'gql',
            },
          ],
        },
      }],
    }
  }]
}

Code generation

By default, this plugin will build typing for your queries automatically to graphql-types.d.ts on every edit. Please note that the definition file should not be placed inside src since this triggers a never ending loop during development.

In order to take advantage of the generated code, user needs to name their query:

// src/pages/index.tsx

  export const pageQuery = graphql`
-   query {
+   query BlogIndex {
      site {
        siteMetadata {
          title
        }
      }
  ...

...and import it from the generated type file:

// src/pages/index.tsx

import { PageProps } from "gatsby";
import { BlogIndexQuery } from '../graphqlTypes'

const BlogIndex: React.FC<PageProps<BlogIndexQuery>> = ({ data, location }) => {
  ...
}