cometkim / gatsby-plugin-typegen

Let's give developers using GatsbyJS better DX with extreme type-safety
https://www.gatsbyjs.org/packages/gatsby-plugin-typegen/
MIT License
204 stars 25 forks source link

Gatsby Build Unknown fragment Error #101

Closed preetjdp closed 4 years ago

preetjdp commented 4 years ago

The Problem

gatsby-plugin-typegen works as expected when running gatsby develop but when I go to build it throws an error. The project where this error occurs can be found here

https://github.com/preetjdp/Blog

Error

[typegen] An error on codegen
    GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".
    GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".

  AggregateError: GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".
      GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".

Version Details

"gatsby-plugin-typegen": "^2.2.1"
"gatsby": "^2.24.47"
"gatsby-plugin-ts-config": "^1.0.0"

Let me know if anything else is required for debugging.

Long Logs

 ⨯ Dell@PREET  D:\..\Blog   master ≣ +1 ~5 -0 !  gatsby build
success open and validate gatsby-configs - 1.229s
success load plugins - 2.333s
success onPreInit - 0.074s
success delete html and css files from previous builds - 0.019s
success initialize cache - 0.061s
success copy gatsby files - 0.223s
success onPreBootstrap - 0.029s
success createSchemaCustomization - 0.269s
success Checking for changed pages - 0.004s                                                              
success source and transform nodes - 16.414s                                                             
success building schema - 0.950s
success createPages - 0.818s
success Checking for changed pages - 0.005s                                                              
success createPagesStatefully - 0.175s
warn There are conflicting field types in your data.

If you have explicitly defined a type for those fields, you can safely ignore this warning message.      
Otherwise, Gatsby will omit those fields from the GraphQL schema.

If you know all field types in advance, the best strategy is to explicitly define them with the
`createTypes` action, and skip inference with the `@dontInfer` directive.
SitePage.context.slug:                                                                                   
 - type: number
   value: 1
 - type: string
   value: '/new-beginnings/'
success update schema - 0.275s
success onPreExtractQueries - 0.036s
success extract queries from components - 1.187s
success write out redirect data - 0.088s

 ERROR 

[typegen] An error on codegen
    GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".
    GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".

  AggregateError: GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".
      GraphQLDocumentError: Unknown fragment "GatsbyImageSharpFixed_noBase64".

  - validate-documents.js:53 Object.checkValidationErrors
    D:/Products/Blog/dist/utils/src/validate-documents.js:53:15

  - codegen.js:63 codegen
    D:/Products/Blog/dist/graphql-codegen-core/src/codegen.js:63:9

  - task_queues.js:62 runNextTicks
    internal/process/task_queues.js:62:5

  - timers.js:429 processImmediate
    internal/timers.js:429:9

  - codegen.js:128
    [Blog]/[gatsby-plugin-typegen]/workers/codegen.js:128:20
cometkim commented 4 years ago

Hey, @preetjdp Thank you for reporting the problem.

When I tried to clone your project and yarn install

The first time I can repro the same problem, but after clean install deps and try again, The problem goes has been disappeared and builds fine.

(for testing, I've only modified a few graphql queries)

diff --git a/gatsby-node.ts b/gatsby-node.ts
index c5c5b5e..d436596 100644
--- a/gatsby-node.ts
+++ b/gatsby-node.ts
@@ -26,12 +26,10 @@ export const createPages = async ({ graphql, actions }: CreatePagesArgs) => {
     `
     {
       github {
-        viewer {
-          repository(name: "Blog") {
-            issues(first: 20, labels: ["Blog"]) {
-              nodes {
-                number
-              }
+        repository(owner: "preetjdp", name: "Blog") {
+          issues(first: 20, labels: ["Blog"]) {
+            nodes {
+              number
             }
           }
         }
@@ -45,7 +43,7 @@ export const createPages = async ({ graphql, actions }: CreatePagesArgs) => {
           }
         }
       }
-    }    
+    }
     `
   )

@@ -57,7 +55,7 @@ export const createPages = async ({ graphql, actions }: CreatePagesArgs) => {

   const { github, allMarkdownRemark } = result.data

-  const ghPosts = github.viewer.repository!.issues.nodes
+  const ghPosts = github.repository!.issues.nodes
   const staticPosts = allMarkdownRemark.edges;

   ghPosts!.forEach((post, _: number) => {
@@ -113,4 +111,4 @@ export const createResolvers: GatsbyNode['createResolvers'] = async ({ createRes
     },
   }
   createResolvers(resolvers, { name: 'default-site-plugin' })
-}
\ No newline at end of file
+}
diff --git a/src/pages/index.tsx b/src/pages/index.tsx
index 73f0570..dcef0b9 100644
--- a/src/pages/index.tsx
+++ b/src/pages/index.tsx
@@ -11,7 +11,7 @@ import { Post, mapNodeToPost } from "../utils/mapPost"
 const BlogIndex = ({ data, location }) => {
   const siteTitle = data.site.siteMetadata.title
   // const posts = data.allMarkdownRemark.edges
-  const posts: Array<Post> = data.github.viewer.repository.issues.nodes.map((e: any) => mapNodeToPost(e));
+  const posts: Array<Post> = data.github.repository.issues.nodes.map((e: any) => mapNodeToPost(e));

   return (
     <Layout location={location} title={siteTitle}>
@@ -80,17 +80,15 @@ export const pageQuery = graphql`
       }
     }
     github {
-      viewer {
-        repository(name: "Blog") {
-          issues(first: 20, labels: ["Blog"]) {
-            nodes {
-              id
-              number
-              title
-              resourcePath
-              createdAt  
-              bodyHTML
-            }
+      repository(owner: "preetjdp", name: "Blog") {
+        issues(first: 20, labels: ["Blog"]) {
+          nodes {
+            id
+            number
+            title
+            resourcePath
+            createdAt
+            bodyHTML
           }
         }
       }
diff --git a/src/templates/blog-post.tsx b/src/templates/blog-post.tsx
index 6fc0494..66b51b3 100644
--- a/src/templates/blog-post.tsx
+++ b/src/templates/blog-post.tsx
@@ -8,7 +8,7 @@ import { rhythm, scale } from "../utils/typography"
 import { Post, mapNodeToPost } from "../utils/mapPost"

 const BlogPostTemplate = ({ data, location }: PageProps) => {
-  const post: Post = mapNodeToPost(data.github.viewer.repository.issue)
+  const post: Post = mapNodeToPost(data.github.repository.issue)
   const siteTitle = data.site.siteMetadata.title

   return (
@@ -61,20 +61,18 @@ export const pageQuery = graphql`
       }
     }
     github {
-      viewer {
-        repository(name: "Blog") {
-          name
-          issue(number: $slug) {
-              id
-                number
-                title
-                resourcePath
-                createdAt  
-                bodyHTML
-                body
-                customHTML
-            }
-        }
+      repository(owner: "preetjdp", name: "Blog") {
+        name
+        issue(number: $slug) {
+            id
+              number
+              title
+              resourcePath
+              createdAt
+              bodyHTML
+              body
+              customHTML
+          }
       }
     }
   }
cometkim commented 4 years ago

You can use the emitting option to make sure the plugin documents are loading properly.

{
      options: {
        emitPluginDocuments: {
          'src/__generated__/gatsby-plugin-documents.graphql': true,
        },
}

Try build with this option and --verbose flag. And check that fragment is in the src/__generated__/gatsby-plugin-documents.graphql

cometkim commented 4 years ago

FYI it seems to work with NPM clean install. but not to work with Yarn. I think there are some resolution issues in your project.

Success log using NPM:

> blog@0.1.0 build /home/cometkim/Workspace/tmp/Blog
> gatsby build "--verbose"

verbose set gatsby_log_level: "verbose"
verbose set gatsby_executing_command: "build"
verbose loading local command from: /home/cometkim/Workspace/tmp/Blog/node_modules/gatsby/dist/commands/build.js
verbose running command: build
success open and validate gatsby-configs - 0.205s
success load plugins - 0.396s
success onPreInit - 0.023s
success delete html and css files from previous builds - 0.005s
success initialize cache - 0.004s
success copy gatsby files - 0.018s
verbose [typegen] Successfully validate your configuration.
{
  "language": "typescript",
  "namespace": "GatsbyTypes",
  "outputPath": "/home/cometkim/Workspace/tmp/Blog/src/__generated__/gatsby-types.ts",
  "includeResolvers": false,
  "autoFix": true,
  "emitSchema": {},
  "emitPluginDocuments": {
    "src/__generated__/gatsby-plugin-documents.graphql": true
  },
  "scalars": {}
}
verbose [typegen] Listen on query extraction
success onPreBootstrap - 0.013s
success createSchemaCustomization - 0.042s
verbose Now have 69 nodes with 9 types: [SitePage:1, SitePlugin:41, Site:1, SiteBuildMetadata:1, GraphQLSource:1, Directory:5, File:11, MarkdownRemark:3, ImageSharp:5]
verbose Checking for deleted pages
verbose Deleted 0 pages
verbose Found 0 changed pages
success Checking for changed pages - 0.009s
success source and transform nodes - 2.142s
success building schema - 0.365s
verbose Now have 73 nodes with 9 types, and 5 SitePage nodes
success createPages - 0.678s
verbose Checking for deleted pages
verbose Deleted 0 pages
verbose Found 4 changed pages
success Checking for changed pages - 0.003s
success createPagesStatefully - 0.065s
warn There are conflicting field types in your data.

If you have explicitly defined a type for those fields, you can safely ignore this warning message.
Otherwise, Gatsby will omit those fields from the GraphQL schema.

If you know all field types in advance, the best strategy is to explicitly define them with the `createTypes` action, and skip inference with the `@dontInfer` directive.
See https://www.gatsbyjs.org/docs/actions/#createTypes
SitePage.context.slug:
 - type: number
   value: 1
 - type: string
   value: '/new-beginnings/'
success update schema - 0.028s
success onPreExtractQueries - 0.001s
success extract queries from components - 0.958s
success write out redirect data - 0.039s
verbose [typegen] End-up listening on query extraction.
verbose [typegen] Emit Gatsby plugin documents into src/__generated__/gatsby-plugin-documents.graphql
verbose [typegen] Generate type definitions to /home/cometkim/Workspace/tmp/Blog/src/__generated__/gatsby-types.ts. (language: TypeScript)
success Build manifest and related icons - 0.168s
success onPostBootstrap - 0.438s
info bootstrap finished - 7.170s
success run page queries - 0.366s - 3/3 8.20/s
success write out requires - 0.005s
warn chunk styles [mini-css-extract-plugin]
Conflicting order. Following module has been added:
 * css ./node_modules/css-loader??ref--12-oneOf-1-1!./node_modules/postcss-loader/src??postcss-2!./src/components/Toggle.css
despite it was not able to fulfill desired ordering with these modules:
 * css ./node_modules/css-loader??ref--12-oneOf-1-1!./node_modules/postcss-loader/src??postcss-2!./src/utils/global.css
   - couldn't fulfill desired order of chunk group(s) component---src-pages-index-tsx, component---src-templates-blog-post-tsx, component---src-templates-static-post-tsx
   - while fulfilling desired order of chunk group(s) component---src-pages-404-js, component---src-pages-using-typescript-tsx
success Building production JavaScript and CSS bundles - 2.242s
[                            ]   0.001 s 0/8 0% Building static HTML for pages
wowza[object Object]
wowza[object Object]
success Building static HTML for pages - 0.743s - 8/8 10.77/s
success onPostBuild - 0.001s
info Done building in 10.688258161 sec

I think you should use yarn or npm, not both.

cometkim commented 4 years ago

I'm closing this.

But you can reopen this anytime if the problem appears after resolving the resolution issue :)

preetjdp commented 4 years ago

@cometkim Thanks for the help., really appreciate it.

I'm gonna try it now.