Giter Site home page Giter Site logo

d4rekanguok / gatsby-typescript Goto Github PK

View Code? Open in Web Editor NEW
122.0 4.0 18.0 8.85 MB

Alternative typescript support plugin for Gatsbyjs. Aims to make using typescript in Gatsby as painless as possible

License: MIT License

JavaScript 14.86% TypeScript 78.57% CSS 6.56%
gatsby gatsby-plugin typescript graphql codegen

gatsby-typescript's Introduction

Gatsby Typescript

An alternative to the official typescript plugin, with ts-loader & automatic type generation for your graphql queries (using graphql-code-generator)


Hi there ๐Ÿ‘‹ Are you just looking for a way to generate graphql types for your graphql queries?

gatsby-plugin-graphql-codegen is what you want. However, other maintainers and I haven't been able to keep this repo up to shape. Please have a look at @cometkim's graphql-plugin-typegen which does almost the same thing & better maintained. Still, ideas & PRs are all welcomed. If you'd like to help maintain this project, please feel free to reach out. Thank you, have a great day!


This monorepo houses 2 packages:

npm package Description Docs
gatsby-plugin-ts alternative typescript support with ts-loader & automated graphql codegen via graphql-code-generator docs
gatsby-plugin-graphql-codegen automated graphql codegen via graphql-code-generator docs

Quick links: Acknowledgement โ€ข General Q&A โ€ข Contribute


Acknowledgment

Special thanks to the contributors, who have improved this project with code, bug reports & suggestions:

Code

@ricokahler (maintainer),

@kije,

@Js-Brecht,

@Kerumen,

@olee,

@Tielem

Bugs & Suggestions

@frantic1048,

@cometkim,

@FrobtheBuilder,

@aswinckr,

@mshick,

@joewood,

@Jdruwe

Do you want to send a PR? see this section

Powered By

This project is built upon these awesome projects:

And of course, Gatsbyjs and Typescript


General Q&A

Here's a list of common questions I've seen since releasing this project. If you have a question that's not here, please don't hesitate to open an issue!

Why use gatsby-plugin-ts?

Gatsby use babel-preset-typescript which strips type information out of your code without doing typecheck. gatsby-plugin-ts use ts-loader, so you don't have to (1) worry about the caveats of babel-preset-typescript or (2) use an IDE / code editor that can typecheck for you.

It also generate typings for your graphql queries, make it easier to strengthen your code.

If you're already using something like VSCode and/or don't want to do typecheck in production, you can toggle off the typecheck option.

What's the difference between gatsby-plugin-ts and gatsby-plugin-graphql-codegen?

Originally belong to the same plugin, the codegen portion was extracted to gatsby-plugin-graphql-codegen so it can be used with the official typescript plugin. If you are already using gatsby-plugin-ts, you don't need gatsby-plugin-graphql-codegen.

Should I check the generated type definition into git?

It's up to your preference.

What is up with all the Maybe<T>?

It's due to Gatsby internal. There's an effort to make typing more strict here.

You also may find the new optional chaining & nullish coalescing operator in typescript 3.7 helpful to deal with this.

Can I turn off type checking and/or type generating?

Yes! You can also use node env to determine whether to enable these features.

// gatsby-config.js
{
  resolve: `gatsby-plugin-ts`,
  options: {
    codegen: false,
    typeCheck: process.env.NODE_ENV === 'development',
  }
},
My graphql queries returns null

Gatsby extract graphql queries statically and it only understand queries inside template literal. It's possible that tsc is transpiling your template literal to string concat quivalent. Check your tsconfig.json & make sure you have a setting similar to this:

"compilerOptions": {
  "target": "ES2018",    /* or at least ES2015 */
  "module": "ESNext",    /* or at least ES2015 */
  "lib": ["dom"],             /* <-- required! */
  "jsx": "preserve",          /* <-- required! */
  "moduleResolution": "node", /* <-- required! */
  /* other options... */
}
What if I have a mixed ts/js codebase?

You'd have to update your tsconfig with the below options:

  "allowJs": true,
  "outDir": "./build"

The outDir option won't be used by ts-loader, but you may need it to satisfy vscode.

Babel doesn't understand the new optional chaining & nullish coalescing syntax even though my IDE shows no errors

If you are using gatsby-plugin-ts, before you go off and install a bunch of babel plugins like a lot of tutorials suggest, check if your compilation target in tsconfig.json is too high (ESNext or ES2019).

With these targets, tsc will leave the new syntax as-is, which babel might not understand. Downgrade them to ES2018 should fix the issue; also make sure your IDE's typescript version is the same as the one listed in your package.json dependency.

Can I write `gatsby-node` in typescript & have its queries typing generated as well?

Yes, but it's not easy at the moment. We're working on it; stay tuned!

Typechecking causes `gatsby develop` to crash.

We're trying to pin down why this happens, please share your experience in #36

Common warning & errors

Gatsby recently moved plugins' fragments from .cache to node_modules. We currently support both paths, but sometimes it may cause conflict warnings & errors:

`warning: Unable to find any GraphQL type definitions for the following pointers ...`

If you are annoyed by this warning, set the documentPaths options as below:

// gatsby-config.js
{
  resolve: 'gatsby-plugin-graphql-codegen',
  options: {
    documentPaths: [
      './src/**/*.{ts,tsx}',
      './node_modules/gatsby-*/**/*.js',
    ],
  }
},

We will remove the .cache/fragments path and bump gatsby peer dependency version in a later release.

Update: Since 2.4.0, we've removed .cache/fragments & bump up gatsby peer dep.

Duplicate identifier error: Duplicate identifier 'GatsbyImageSharpFixedFragment'

If you see this error please run a gatsby clean to remove fragments in .cache, or set the documentPaths options as below:

// gatsby-config.js
{
  resolve: 'gatsby-plugin-graphql-codegen',
  options: {
    documentPaths: [
      './src/**/*.{ts,tsx}',
      './node_modules/gatsby-*/**/*.js',
    ],
  }
},
Missing definition Unknown identifier 'GatsbyImageSharpFixedFragment' in a yarn/lerna monorepo

Are you using a monorepo? It's possible that the missing fragment's plugin is 'hoisted' (moved to workspace root's node_modules). A simple fix is use a nohoist config, supported by both lerna & yarn. Here's an example with yarn workspace, where gatsby-transformer-sharp is always installed in its project's node_modules.

in your root's package.json

"workspaces": {
  "packages": ["packages/*"],
  "nohoist": [
    "**/gatsby-transformer-sharp"
  ]
}

Contribute to this repo

All PRs / issues are welcomed.

Steps to run in development:

# 0
git clone https://github.com/d4rekanguok/gatsby-typescript.git && cd gatsby-typescript

# 1 Install deps
yarn

# 2 Hook up dependencies
yarn bootstrap

# 3 Build binaries
lerna run build

# 4 Run test
yarn test

You can test your code against the starters inside the repo. Don't forget to checkout the changes in those repo before sending a PR. Alternatively, use yalc to test the plugins in your own Gatsby project:

# 1 Install yalc
npm i yalc -G

# 2 cd into, say, gatsby-plugin-ts
cd packages/gatsby-plugin-ts

# 3 Publish to yalc
yalc publish

# 4 cd into your gatsby project
cd ../../my-gatsby-project

# 5 Install yalc & re-install deps
npm uninstall gatsby-plugin-ts && yalc add gatsby-plugin-ts

npm install

# 6 Subsequent update
yalc update

# 7 Done? remove yalc deps
yalc remove --all

gatsby-typescript's People

Contributors

alvis avatar d4rekanguok avatar darylwright avatar dependabot[bot] avatar jackschu avatar js-brecht avatar kajirikajiri avatar kdichev avatar kerumen avatar kije avatar olee avatar ricokahler avatar tielem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gatsby-typescript's Issues

Error from gatsby-plugin-graphql-codegen v.2.1.4

I'm seeing the following error when using the latest version:

results.filter(...).flat is not a function

  TypeError: results.filter(...).flat is not a function
  
  - graphql-codegen.config.js:88 

It looks like TypeScript is not transpiling array.flat. The reason for this is that flat has moved from esnext to es2019. If you change you lib array in tsconfig to include es2019 it should fix it:

https://github.com/d4rekanguok/gatsby-typescript/blob/master/packages/gatsby-plugin-graphql-codegen/tsconfig.json#L6

Should be:

  "lib": ["dom", "esnext", "es2019"], 

Run gatsby-node with ts-node?

I'm not sure if you've considered this, or if it's even possible for a plugin to do this, but could there be a way to make Gatsby run the gatsby-node file using ts-node? Again, I don't actually know whether or not this would require a change to Gatsby's core or if a plugin could force it. Just wondering if it's something you've looked into.

On build errors the output file can be wiped

When working on files while gatsby develop is running, sometimes a change causes the plugin to regenerate the output and it does almost seem like it nukes the file, before writing new output.
I checked the code, it's not what it's actually happening. I guess the codegen phase fails when the process is triggered while working on the code and there are build errors which is probably causing empty output being written.

Whilst working code generation tools in the past, it has sometimes proven to be helpful to only write, only after checking that the new output is different and only then actually touching the file - as build tools sometimes trigger rebuilds / invalidate caches just based on file modification times. I am not quite sure, if Gatsby would do that or not.

Obviously just keeping the existing file as it is, is somewhat misleading / undeterministic, as it might not be in sync with the present types in that moment, but it does seem like it could be at least a helpful option to improve developer ergonomics what this is all about in the end.

[codegen] Detach codegen from gatsby lifecycle

Not sure if this should be the way to move forward. This will allow us to provide a smoother experience for 100% typescrip codebase, i.e generating typings for queries in both gatsby-node and src/**/*.ts{x}.

Current problems:

  • Gatsby don't watch gatsby-node, or files outside of src
  • Typegen doesn't happen until onPostBootstrap. If user changes their query in gatsby-node and the new type is not yet generated, error will be thrown & prevent a new build.

We don't have to go heavy on this, i.e creating a separate process. Perhaps a webpack plugin? Not sure yet ... need some more thinking...

Also, I wish we knew a bit more about Gatsby's plan on supporting TS in v3! :)

Missing fragments on Mac Os

Whenever I try to run graphql codegen on my mac, I get the following error:

image

It seems to work fine on Linux (running Pop!_os 19.10). I believe it has to be related to the differences in paths of Mac os. By the way, I have gatsby-plugin-sharp dep. which hosts the fragments.

Feature request: gatsby-node codegen

Objective

The following is a feature request to add codegen for gatsby-node related typescript files so that calls to graphql via the createPages node API are typed.

My gatsby-node.js file looked something like this:

// gatsby-node.js
const nodeTsConfig = {/* ... */};
require('ts-node').register(nodeTsConfig);
const createShopPage = require('./create-shop-page.ts').default;

exports.createPages = async args => {
  await createShopPage(args);
};

I use ts-node to load typescript files from gatsby-node.js.

The following ๐Ÿ‘‡ is an example typescript file imported from gatsby-node.js

// create-shop-page.ts
import { CreatePagesArgs } from 'gatsby';
async function createShopPage({
  actions: { createPage },
  graphql,
}: CreatePagesArgs) {
  //       ๐Ÿ‘‡ the goal is to generate types for this
  const { data } = await graphql(`
    query CreateShopPage {
      wpgraphql {
          products(first: 5) {
            nodes {
              name
              slug
            }
          }
        }
      }
  `);

  // ...
}

export default createShopPage;

As stated in the comment above, the goal of this feature request is to add types for data.

Assessment

The Magic Comment

After a lot of digging and even opening up other related feature requests, I found out that graphql-code-generator already supports generating types from inside gatsby-node's await graphql(/* ... */) calls via a "magic comment".

This means that simply adding the comment /* GraphQL */ inline to the graphql(/* ... */) call will make graphql-codegen create types for the CreateShopPage query:

// create-shop-page.ts
import { CreatePagesArgs } from 'gatsby';
async function createShopPage({
  actions: { createPage },
  graphql,
}: CreatePagesArgs) {
  //  adding this enables types to be generated for `CreateShopPage`
  //                                  ๐Ÿ‘‡
  const { data } = await graphql(/* GraphQL */ `
    query CreateShopPage {
      wpgraphql {
          products(first: 5) {
            nodes {
              name
              slug
            }
          }
        }
      }
  `);

  // ...
}

export default createShopPage;

And additionally, the next release of graphql-codegen will make it so that you don't need the magic comment.

Issues with onPostBootstrap

The current implementation runs codegen after bootstrapping via onPostBootstrap, and the createPages is run before onPostBoostrap.

This is an issue because if there are types generated that are needed to create pages, then those types will not have been generated yet (via onPostBoostrap).

Recommendations

  • Add some documentation saying that gatsby-node codegen is supported via the "magic comment" (until the next graphql-codegen is released).
  • Move the codegen from onPostBootstrap to createPages. I currently have this working by running some code during createPages before I require(/* ... */) the typescript file.

My gatsby-node.js currently looks like this:

const codeGenGatsbyNode = require('./code-gen-gatsby-node');
const nodeTsConfig = require('./src/create-pages/tsconfig.json');
require('ts-node').register(nodeTsConfig);

exports.createPages = async args => {
  await codeGenGatsbyNode(args);

  const createPages = require('./src/create-pages').default;
  return createPages(args);
};
  • codeGenGatsbyNode runs code gen
  • create-pages is a typescript file that uses the generated types

Let me know what you think! I'd be willing to work on this feature if you see fit.

Thanks a bunch!

Should split codegen into its own repo?

  • ts-loader is slower than babel Actually since we're not type checking with tsc, ts-loader is only tiny bit slower than babel. Yay!

  • typecheck can still be done independently via ts-fork-typecheck webpack plugin or with IDE

  • codegen part will be more useful for everyone, regardless of which ts plugin they use

  • We'll turn this repo into a monorepo that host the current gatsby-plugin-ts and the gatsby-plugin-graphql-codegen

  • Remove duplicate code from gatsby-plugin-ts without breaking changes

[codegen] Improve DX: generate a [filename].type.ts that contain data type for each [filename].tsx

Currently, you have to...

  • name your query
  • mentally add 'Query' suffix to your query name
  • import it from '../../graphql-types'
  • use it in your IProps or useStaticQuery<MyQuery>

Even though it's a set it & forget it type of thing, it still sucks. I propose we generate a [filename].type.ts next to the [filename] itself, and export the query type right there. So the flow would be more like this:

  • import Data (alias for your query data) from [filename].type
  • use it

So from this

import * as React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import { ImageQuery } from '../../graphql-types'

export const Image = () => {
  const data = useStaticQuery<ImageQuery>(graphql(`...`))
  return (...)
}

To this

import * as React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import { Data } from './image.type'

export const Image = () => {
  const data = useStaticQuery<Data>(graphql(`...`))
  return (...)
}

I think this is a better experience. We can infer the file location from Gatsby's generated name for unnamed query. It'll be interesting for dual schema codebase, since I don't know yet how to handle that...

Problems: More loose part, I don't know how reliably we can infer the location / query name, and even if that's stable, the codebase will definitely be more complex complicated.

Any feedback is appreaciated!

Allow codegen for non-gatsby schemas

I apologize if this issue is specific however I don't know where else to post about it.

It's sort of an issue with graphql-codegen but also specific to codegen in a gatsby context via this plugin so I'll start here ๐Ÿ˜…

Please let me know if I missed something!

The issue

Using the @apollo/client (v3.0.0-beta.32), requires you import the gql tag from apollo like so:

import { useQuery, gql } from '@apollo/client';

// ๐Ÿ”ด gatsby-plugin-graphql-codegen will try to create types using the wrong schema
const myQuery = gql`
  // ...
`;

The issue is, when I do this, graphql-codegen will try to create types for this query using the Gatsby schema. This is an issue because the Apollo client I have set up should point to a different graphql schema than the schema created via gatsby during build time.

The workaround

I have a temporary workaround of importing gql via require like so:

// โœ… gatsby-plugin-graphql-codegen will ignore this
const { gql: apolloGql } = require('@apollo/client');

const myQuery = apolloGql`
  // ...
`;

Recommendations

At the minimum, it would be nice if it were possible to add some sort of way to ignore codegen for particular patterns (e.g. importing from @apollo/client). This way this plugin stays focused on just doing codegen for gatsby related queries.

Going all in, we could work towards this plugin officially supporting the Apollo client via allowing an additional non-gatsby schema and generating a different types file per the type of graphql tag. I'm not too sure how to get this working or even it makes sense but hopefully this will inspire.

Thanks for any help!

(gatsby-plugin-ts) Error with latest Gatsby

ERROR #98123 WEBPACK

Generating SSR bundle failed

Cannot find module '@babel/preset-typescript' from '/Users/derek/Documents/Documents/Projects/opensource/byderek.com'

File: .cache/api-ssr-docs.js

Likely Gatsby internal assuming presence of gatsby-plugin-typescript? Need to look into this more

Cannot find module 'typescript'

Do I have for that plugin to work properly to install TS locally in project DIR?
Here is the error I am getting while having TS globally:


 ERROR #11321  PLUGIN

"gatsby-plugin-ts" threw an error while running the onCreateWebpackConfig lifecycle:

Cannot find module 'typescript'
Require stack:
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/fork-ts-checker-webpack-plugin/lib/index.js
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby-plugin-ts/gatsby-node.js
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/resolve-module-exports.js
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/load-plugins/validate.js
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/load-plugins/load.js
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/load-plugins/index.js
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/index.js
- /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/commands/develop.js
- /Users/mkbctrl/.config/yarn/global/node_modules/gatsby-cli/lib/create-cli.js
- /Users/mkbctrl/.config/yarn/global/node_modules/gatsby-cli/lib/index.js

  61 |     var plugins = [];
  62 |     if (typeCheck) {
> 63 |         plugins.push(new fork_ts_checker_webpack_plugin_1.default(forkTsCheckerPlugin));
     |                      ^
  64 |     }
  65 |     var config = {
  66 |         module: {

File: node_modules/gatsby-plugin-ts/gatsby-node.js:63:22



  Error: Cannot find module 'typescript'
  Require stack:
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/fork-ts-checker-webpack-plugin/lib/index.js
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby-plugin-ts/gatsby-node.js
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/resolve-module-exports.js
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/load-plugins/validate.js
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/load-plugins/load.js
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/load-plugins/index.js
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/bootstrap/index.js
  - /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/gatsby/dist/commands/develop.js
  - /Users/mkbctrl/.config/yarn/global/node_modules/gatsby-cli/lib/create-cli.js
  - /Users/mkbctrl/.config/yarn/global/node_modules/gatsby-cli/lib/index.js

when I install the TS locally, then I have shitstorm while trying to gatsby develop....

ERROR in /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/typescript/lib/lib.dom.d.ts(5720,13):
5720:13 Duplicate identifier 'FormData'.
    5718 | }
    5719 | 
  > 5720 | declare var FormData: {
         |             ^
    5721 |     prototype: FormData;
    5722 |     new(form?: HTMLFormElement): FormData;
    5723 | };


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/typescript/lib/lib.dom.d.ts(16123,11):
16123:11 Duplicate identifier 'URLSearchParams'.
    16121 | declare var webkitURL: typeof URL;
    16122 | 
  > 16123 | interface URLSearchParams {
          |           ^
    16124 |     /**
    16125 |      * Appends a specified key/value pair as a new search parameter.
    16126 |      */


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/typescript/lib/lib.dom.d.ts(16156,13):
16156:13 Duplicate identifier 'URLSearchParams'.
    16154 | }
    16155 | 
  > 16156 | declare var URLSearchParams: {
          |             ^
    16157 |     prototype: URLSearchParams;
    16158 |     new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
    16159 |     toString(): string;


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/typescript/lib/lib.dom.d.ts(20034,6):
20034:6 Duplicate identifier 'RequestInfo'.
    20032 | type HeadersInit = Headers | string[][] | Record<string, string>;
    20033 | type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;
  > 20034 | type RequestInfo = Request | string;
          |      ^
    20035 | type BlobPart = BufferSource | Blob | string;
    20036 | type DOMHighResTimeStamp = number;
    20037 | type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext;


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in /Users/mkbctrl/Documents/Developer/SI/gatsby-bootcamp/node_modules/typescript/lib/lib.dom.d.ts(20227,6):
20227:6 Duplicate identifier 'XMLHttpRequestResponseType'.
    20225 | type WebGLPowerPreference = "default" | "high-performance" | "low-power";
    20226 | type WorkerType = "classic" | "module";
  > 20227 | type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
          |      ^
    20228 | 

and so on....

Anyone had similar issues?

Types not generated for all files, ambiguous build error

It worked once, then decided to quit on me. I'm using gatsby-plugin-graphql-codegen with the default config, not gatsby-plugin-ts. It's very possible I've just done something wrong; I'm new to gatsby and graphql both, but this error message isn't very useful:

warn [gatsby-plugin-graphql-codegen] Cannot read property 'buildError' of undefined
info [gatsby-plugin-graphql-codegen] definition for queries of schema default-gatsby-schema has been updated at

Types are being generated, but missing for at least one file:

import React from 'react';
import { graphql } from 'gatsby';
import { QueryBlogPostBySlug } from '../../graphql-types'; // type error; module graphql-types has no exported member QueryBlogPostBySlug

interface BlogPostProps {
  data: QueryBlogPostBySlug;
}

const BlogPost: React.FC<BlogPostProps> = props => {
  // ...
};

export const query = graphql`
  query BlogPostBySlug($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    allButterPost(filter: { slug: { eq: $slug } }) {
      edges {
        node {
          id
          body
          seo_title
          date
          categories {
            name
          }
        }
      }
    }
  }
`;

export default BlogPost;

My query looks fine and runs fine, so I'm not sure what I'm missing. Repo is here.

Gatsby develop crashes on type errors

I am just converting a rather small gatsby project to typescript using this awesome plugin. It seems to be a lot better than the default typescript plugin.

But I have come across one quite annoying behavior: When running gatsby develop it seems to crash after some type errors occured. Here is an example:

ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in /....../src/templates/DogTemplate.tsx(73,33):
TS2605: JSX element type '{} | null' is not a constructor function for JSX elements.
  undefined

not finished Generating image thumbnails - 61.696s


0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'develop' ]
โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”
16 pages                                             In Progress                                             bsf-website
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] develop: `gatsby develop`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] develop script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/xxx/.npm/_logs/2020-02-01T22_09_00_221Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `npm run develop`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/xxx/.npm/_logs/2020-02-01T22_09_00_248Z-debug.log

This can be quite annoying as type errors are expected during development and the dev server should simply display those errors on a console (ideally in browser and terminal) without crashing.

Is this a known behavior or is it something I'm doing wrong on my end?

graphql-toolkit throws error about no type def found since gatsby-plugin-ts 1.3.2

On gatsby-plugin-ts 1.3.0 and 1.3.1, during building, graphql-toolkit only warns with a message like this:

Unable to find any GraphQL type defintions for the following pointers: <Project Root>/.cache/fragments/*.js

On [email protected], graphql-toolkit throws an error with the above message, which breaks building. I found 1.3.2 is a greenkeeping version, and updated graphql-toolkit. Maybe it's caused by graphql-toolkit's internal change.

Related source code: https://github.com/d4rekanguok/gatsby-plugin-ts/blob/4d5e6fae7507c7cfe15b7584fa26aac021352bb7/src/graphql-codegen.config.ts#L26-L29

Bug in [email protected] when used with [email protected]

Emits error:

AggregateError: GraphQLDocumentError: Fragment "GatsbyImageSharpFixed" is never used.

Here is the full log.

In case it helps, these are the versions of some of the potentially related dependencies I'm using:

{
    "apollo-boost": "^0.4.7",
    "gatsby": "^2.20.12",
    "gatsby-image": "^2.3.1",
    "gatsby-plugin-graphql-codegen": "^2.7.0",
    "gatsby-plugin-sharp": "^2.5.3",
    "gatsby-plugin-typescript": "^2.3.1",
    "gatsby-plugin-typescript-checker": "^1.1.1",
    "gatsby-transformer-sharp": "^2.4.3",
    "graphql": "^15.0.0",
    "graphql-cli": "^3.0.14",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "typescript": "^3.8.3"
}

UPDATE:

The problem appears when used with [email protected]. It works fine with graphql v14.6.0.

Testing with Jest

Per our discussion here: #39 (comment)

We wanted to add tests with jest. I wanted to open this issue to track how we'll do that.

Here's a few questions:

Testing conventions

What conventions do you prefer?

  1. it('blah', () => {}) or test('blah', () => {})?
  2. do you want omit top-level describe or prefer to keep it?
  3. file.spec.ts or file.test.ts?
  4. What folder structure do you prefer? separate or inline?

Separate: a tests folder next to src at the root or

/gatsby-plugin-graphql-codegen
|-/src
  |-gatsby-node.ts
|-/tests
  |-gatsby-node.test.ts

Inline: a test file in the same src folder?

/gatsby-plugin-graphql-codegen
|-/src
  |-gatsby-node.ts
  |-gatsby-node.test.ts

I prefer inline test files because it makes me care more about the tests but I don't mind either convention.

CI and Coverage Reporting

Do you have any preference for tools? I've only really used travis and coveralls but idk maybe those tools are out of style? I can defer to you to set that up but it we're testing we might as well talk about CI and coverage reporting

__typename mutated to _xtypename by codegen

I am currently working on a Gatsby project using Contentful, that I am trying to move to TS, and we use __typename to differentiate certain contents as the rest of the object is the same.

We therefore request the __typename in the query for these but codegen is oddly returning _xtypename in the type?

// Type returned
Screenshot 2020-03-13 at 07 24 09

// Query
Screenshot 2020-03-13 at 07 25 14

  • gatsby: ^2.19.18, (2.19.18 in lock)
  • gatsby-plugin-ts: ^2.4.0"
  • typescript: 3.8.3

Conflicting graphql module

Error: Cannot use GraphQLDirective "@Skip" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.

Looks like we'd need to revert #17

Inline Fragments aren't exported

I'm experimenting with Gatsby + TypeScript, while having gatsby-plugin-graphql-codegen generate all types which come from GraphQL. Using this with inline fragments + interfaces doesn't export the types for the fragments to be consumed by components' props. This means I'd have to duplicate types for all widgets.

Please export the fragments as well.

Example:

export const createSchemaCustomization = ({
  { createTypes },
}: CreateSchemaCustomizationArgs) => {
  const typeDefs = `
    type Image {
      src: File! @fileByRelativePath
      alt: String
      caption: String
    }
    interface Widget {
      widgetId: String!
      widgetType: String!
    }
    type ImageSliderWidget implements Widget {
      widgetId: String!
      widgetType: String!
      images: [Image!]!
    }
    type ImageWidget implements Widget {
      widgetId: String!
      widgetType: String!
      image: Image
    }
  `;

  createTypes(typeDefs);
}

export const ImageFragment = graphql`
  fragment ImageFragment on Image {
    src {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }
    alt
    caption
  }
`;

export const WidgetFragment = graphql`
  fragment WidgetFragment on Widget {
      widgetId
      widgetType
      ... on ImageListWidget {
        images {
          ...ImageFragment
        }
      }
      ... on ImageWidget {
        image {
          ...ImageFragment
        }
      }
    }
  `

Now when it comes time to generate the <ImageWidget />, I could type using the generated Fragment types, which are not exported from graphql-types.ts:

type WidgetFragment_ImageSliderWidget_Fragment = (
  Pick<ImageSliderWidget, 'widgetId' | 'widgetType'>
  & { images: Array<Maybe<ImageFragmentFragment>> }
);

type WidgetFragment_ImageWidget_Fragment = (
  Pick<ImageWidget, 'widgetId' | 'widgetType'>
  & { image: Maybe<ImageFragmentFragment> }
);

The whole WidgetFragment definition is exported, but there's no way to get the definition I need from it:

export type WidgetFragmentFragment = WidgetFragment_ImageSliderWidget_Fragment | WidgetFragment_ImageWidget_Fragment;

Provide an option to disable the typechecker entirely

At the very least this would help in debugging. I'm currently experiencing an issue where my preview server running in a docker container is failing, and I believe it's due to the typechecker, but it's quite difficult to debug.

[codegen] Make `additionalSchemas` configuration easier

Current minimal setup:

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

Considering that most users would have only 1 additional schema, we should:

  1. Check if additionalSchemas is an array or object, so user can just pass in an object directly
  2. Remove key. Make key optional. Create a key automatically based on schema path
  3. Make fileName optional. Use a sensible default like graphql-types-addition, if additionalSchemas is an array, append a number
  4. Make pluckConfig optional. User only needs to pass in name & identifier

So ideally, most users should only need to do this:

exports.default = {
  plugins: [{
    resolve: `gatsby-plugin-graphql-codegen`,
    options: {
      additionalSchemas: {
        schema: 'https://graphql-pokemon.now.sh/',
        //  import gql from 'graphql-tag'
        gqlIdentifier: ['gql', 'graphql-tag']
      },
    }
  }]
}

Endless definition updates even when nothing goes on

info [gatsby-plugin-graphql-codegen] definition for queries of schema default-gatsby-schema has been updated at ./src/lib/gatsby-graphql.ts
success extract queries from components - 0.059s
info [gatsby-plugin-graphql-codegen] definition for queries of schema default-gatsby-schema has been updated at ./src/lib/gatsby-graphql.ts
success extract queries from components - 0.055s
info [gatsby-plugin-graphql-codegen] definition for queries of schema default-gatsby-schema has been updated at ./src/lib/gatsby-graphql.ts
success extract queries from components - 0.092s
info [gatsby-plugin-graphql-codegen] definition for queries of schema default-gatsby-schema has been updated at ./src/lib/gatsby-graphql.ts
success extract queries from components - 0.076s
info [gatsby-plugin-graphql-codegen] definition for queries of schema default-gatsby-schema has been updated at ./src/lib/gatsby-graphql.ts
success extract queries from components - 0.110s

Setup is 100% per readme, nothing special. Editor is WebStorm, just in case.

Indeterministic output causes unnecessary diffs in SCM

The order of some properties does seem indeterministic. I decided to track the file in Git, as I have a Git Hook in place to build all TypeScript which relies on the generated types and I want to be sure it works without having to run gatsby develop beforehand. Unfortunately the output doesn't seem deterministic, so the file has changes because the order of properties in the types changes.

Example of such a diff:

@@ -2260,15 +2260,15 @@ export type SitePage = Node & {
   internalComponentName: Scalars['String'];
   componentChunkName: Scalars['String'];
   matchPath?: Maybe<Scalars['String']>;
+  id: Scalars['ID'];
+  parent?: Maybe<Node>;
+  children: Array<Node>;
+  internal: Internal;
   isCreatedByStatefulCreatePages?: Maybe<Scalars['Boolean']>;
   context?: Maybe<SitePageContext>;
   pluginCreator?: Maybe<SitePlugin>;
   pluginCreatorId?: Maybe<Scalars['String']>;
   componentPath?: Maybe<Scalars['String']>;
-  id: Scalars['ID'];
-  parent?: Maybe<Node>;
-  children: Array<Node>;
-  internal: Internal;
 };

Auto publish starters via Github Actions

Per our discussions in #41 and #42 , I think it makes sense to run a gatsby build as a required status check before merging a PR.

Here's my idea:

Since you already have the gatsby-starter-blog-ts package in there, let's create a GitHub Workflow that will link the packages via lerna and then simply run gatsby build and see if it succeeds. This is kind of nice because you get the confidence that the plugins are working as well as gatsby-starter-blog-ts.

Let me know what you think. I can experiment in my fork if I get your blessing.

[Question] ES5

Hey, since in the docs you ask to set at least ES2015 as a target, can you please tell me what will happen if I will use ES5? Can't find any information about what can break.

Thanks in advance!

moduleResolution "gotcha" in required tsconfig settings

If you want "target": "esnext" and "module": "esnext" to work properly with a project that uses, well, any npm packages at all (including Gatsby itself), you absolutely must specify "moduleResolution": "node". Without it, tsc won't even bother looking in node_modules for typings, since it defaults to "classic" if you're using any module setting other than "commonjs". It would be worth noting this in the readme.

camel case vs snake case

I've used the search in hope for a duplicate.

I'm currently using the https://rickandmortyapi.com/ graphql api.

The types being generated by gatsby-plugin-graphql-codegen are a mixture of camel case and snake case (e.g: RickAndMorty_Characters), is there a way of configuring that? Either to only have camel case or snake case?

Thanks

Working example (with a mixed js/ts codebase)?

I've been having a bear of a time getting this working in existing projects, so I went back to basics:

  1. Install gatsby-starter-default
  2. npm install gatsby-plugin-ts typescript
  3. tsc --init and incorporate required settings, as well as allowJs: true
  4. Add the following to my gatsby-config
    {
      options: {
        alwaysCheck: false,
        codegen: true,
        codegenDelay: 250,
        fileName: "./graphql-types.ts",
        tsLoader: {
          logLevel: "warn",
        },
      },
      resolve: `gatsby-plugin-ts`,
    },
  1. Rename index.js -> index.tsx
  2. npm run build -> no problems
  3. npm run develop -> loads of errors:
 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in undefined(undefined,undefined):
TS5055: Cannot write file '/my-default-starter/gatsby-browser.js' because it would overwrite input file.


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in undefined(undefined,undefined):
TS5055: Cannot write file '/my-default-starter/gatsby-config.js' because it would overwrite input file.


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in undefined(undefined,undefined):
TS5055: Cannot write file '/my-default-starter/gatsby-node.js' because it would overwrite input file.


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in undefined(undefined,undefined):
TS5055: Cannot write file '/my-default-starter/gatsby-ssr.js' because it would overwrite input file.


 ERROR #98123  WEBPACK

Generating SSR bundle failed

ERROR in undefined(undefined,undefined):
TS5055: Cannot write file '/my-default-starter/public/1-cce43242f980203bd522.js' because it would overwrite input file.

and on for all files with a .js extension

Are there examples of this plugin working for folks in the wild? It seems that the type checking config is somehow off.

Cannot read property 'definitions' of undefined

I tried to use the gatsby-plugin-graphql-codegen on my gatsby site but i'm unable to develop my gatsby site. Am i missing something? Appreciate your help!

On my terminal -

 ERROR

Cannot read property 'definitions' of undefined

  TypeError: Cannot read property 'definitions' of undefined

  - index.cjs.js:397 Promise.all.documentFiles.map
    [frontend]/[@graphql-toolkit]/common/index.cjs.js:397:69

  - Array.map

  - index.cjs.js:394 Object.validateGraphQlDocuments
    [frontend]/[@graphql-toolkit]/common/index.cjs.js:394:50

gatsby-config.js :

{
      resolve: `gatsby-plugin-graphql-codegen`,
},

pages/work.tsx

const Work = ({ data }: any) => (
  <Layout>
    {console.log(data)}
    <SEO title="Work" keywords={[`work`, `portfolio`, `react`]} />
    <h1>This is where I showcase my work</h1>
    <Link to="/about/">Go to page 2</Link>
  </Layout>
);

export const query = graphql`
  query WorksData {
    allSanityWork {
      nodes {
        title
      }
    }
  }
`;

export default Work;

[update: 1.3] Typecheck is now disabled during production

In my medium-sized gatsby repo, disabling typecheck during production shaves off roughly 5 seconds in build time, or about 7%. This is not that significant (since the bulk of the build time hang up is due to fetching resources from where else), but I think it's still worth it to set this option by default. To reverse this behavior, users can set alwaysCheck options:

{
  resolve: `gatsby-plugin-ts`,
  options: {
    alwaysCheck: true, // check type no matter what
  }
}

We're technically breaking semver, but it's very unlikely that a type error occurs during production, but not development... If someone does run into issue because of this, I'm really sorry & please let me know!

[docs] Advice users to install `graphql` directly to avoid walls of peer deps warning

When users install the plugin to their site, they'll met with 10s of dependencies warnings for graphql.
We have to use Gatsby's own graphql (gatsby/graphql). I'm not sure how to fix this?

Here's the messages:

Dereks-MacBook-Pro-2:test-ts derek$ yarn add gatsby-plugin-ts
yarn add v1.16.0
[1/4] ๐Ÿ”  Resolving packages...
[2/4] ๐Ÿšš  Fetching packages...
[3/4] ๐Ÿ”—  Linking dependencies...
warning "gatsby-plugin-ts > graphql-toolkit > [email protected]" has unmet peer dependency "graphql@^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > @graphql-codegen/[email protected]" has unmet peer dependency "graphql@^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > [email protected]" has unmet peer dependency "graphql@^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > @graphql-codegen/core > @graphql-codegen/[email protected]" has unmet peer dependency "graphql@^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > @graphql-codegen/typescript > @graphql-codegen/[email protected]" has unmet peer dependency "graphql@^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > graphql-toolkit > [email protected]" has unmet peer dependency "graphql@^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > @graphql-codegen/typescript > @graphql-codegen/visitor-plugin-common > [email protected]" has unmet peer dependency "graphql@^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > graphql-toolkit > graphql-tools > [email protected]" has unmet peer dependency "graphql@^0.11.3 || ^0.12.3 || ^0.13.0 || ^14.0.0".
warning "gatsby-plugin-ts > graphql-toolkit > graphql-tools > [email protected]" has unmet peer dependency "graphql@^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".

TS2307: Cannot find module 'csstype'

If you're running Gatsby with this plugin for the first time, you might see this error.

Error: /test-ts/node_modules/@types/react/index.d.ts
ERROR in /test-ts/node_modules/@types/react/index.d.ts(29,22):
TS2307: Cannot find module 'csstype'.

Changing moduleResolution in tsconfig to node will fix this:

    /* Module Resolution Options */
    "moduleResolution": "node",

Here's a helpful comment about the error.

This is not a problem with this plugin, but if you're trying to use it, you might run into this -- because of that I post it here for visibility. Will update the readme shortly to add this, also, in the next version I'll add some check in the plugin to make sure tsconfig is configurated correctly.

check `options.fileName` directory existence before writing file

I configured options.fileName under a separate directory in the project root for generated code, and gitignored it.

Then I found a quick failing on CI, errored with: Error: ENOENT: no such file or directory, open <options.fileName>.

After minutes I found the error is thrown from gatsby-plugin-ts ( https://github.com/d4rekanguok/gatsby-plugin-ts/blob/a31a61c76b237a76dc52274c699e5b9d1f3d97e6/src/graphql-codegen.config.ts#L66 ).

I think it's a good practice to check directory existence before writing to a user-defined pathname. Also, it could be more user-friendly ( อกยฐ อœส– อกยฐ).

On the other hand, whitelisting a blank directory for generated code in .gitigore is also considerable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.