3.1.0 • Published 1 year ago

gatsby-plugin-typegen v3.1.0

Weekly downloads
8,049
License
MIT
Repository
github
Last release
1 year ago

gatsby-plugin-typegen

Watch changes, Automatically generates TypeScript definitions.

  • Schema extraction
  • Generates code using graphql-codegen
  • Options to customize paths
  • Auto-fixing <StaticQuery> and useStaticQuery() with generated type name.

Demonstration auto-fixing

Requirements

  • Node v10.0.0 +
  • GatsbyJS v2 +

Install

yarn add gatsby-plugin-typegen

# or
# npm install --save gatsby-plugin-typegen

How to use

// In your gatsby-config.js
plugins: [`gatsby-plugin-typegen`]

Also you can customize output path of generated files.

// Example of type-safe usage (optional)
import { PluginOptions as TypegenPluginOptions } from 'gatsby-plugin-typegen';

type Plugin = (
  | string
  | { resolve: string, options: any }
  | { resolve: `gatsby-plugin-typegen` options: TypegenPluginOptions }
);

const plugins: Plugin[] = [
  {
    resolve: `gatsby-plugin-typegen`,
    options: {
      schemaOutputPath: `${__dirname}/.cache/caches/gatsby-plugin-typegen/schema.json`,
      typeDefsOutputPath: `${__dirname}/node_modules/generated/types/gatsby.ts`,
    },
  },
];

module.exports = {
  plugins,
};

Available options

  • schemaOutputPath: (string?) Path to where the schema file is being generated.

  • typeDefsOutputPath: (string?) Path to where the type definition file is being generated.

  • autoFix: (boolean?) Enable auto-fixing static queries with generated types.

ESLint

You can use the extracted schema file for eslint-plugin-graphql!

// In a file called .eslintrc.js
module.exports = {
  rules: {
    'graphql/template-strings': ['error', {
      env: 'relay',
      schemaJsonFilepath: `${__dirname}/.cache/caches/gatsby-plugin-typegen/schema.json`,
      tagName: 'graphql',
    }],
  },
  plugins: [
    'graphql'
  ]
};

You may get error for first time because schema is not extracted in your .cache dir yet.

Acknowledgements