Graphql-code-generator: Question: Does Code Generator find GraphQL queries as strings inside .ts/.tsx files?

Created on 8 Aug 2019  ·  3Comments  ·  Source: dotansimha/graphql-code-generator

Describe the bug

This might be me misunderstanding. But reading the Documents section from the documentation, I thought I could generate Typescript definintions from random query .. strings in my source code.

Using graphql-tag and wrapping my query strings work though. I'm using raw strings since it's simple, and since it works with the GraphQL client I'm currently using.

When running without graphql-tag, it fails with:

> graphql-codegen

  ✔ Parse configuration
  ❯ Generate outputs
    ❯ Generate ./graphql-types.ts
      ✔ Load GraphQL schemas
      ✖ Load GraphQL documents
        → Unable to find any GraphQL type defintions for the following pointers: src/foo.ts
        Generate


 Found 1 error

  ✖ ./graphql-types.ts
    Error: Unable to find any GraphQL type defintions for the following pointers: src/foo.ts


Something went wrong

To Reproduce
Steps to reproduce the behavior:

  1. My GraphQL operations:

This does not work:

const USER_QUERY = `
    query UserQuery($userId: ID!) {
        user(_id: $userId) {
          name
        }
    }
`;

This works:

import gql from 'graphql-tag';

const USER_QUERY = gql`
    query UserQuery($userId: ID!) {
        user(_id: $userId) {
          name
        }
    }
`;
  1. My codegen.yml config file:
{
  "schema": "http://localhost:4000/graphql",
  "documents": "src/foo.ts",
  "generates": {
    "./graphql-types.ts": {
      "plugins": [
        "typescript",
        "typescript-operations"
      ]
    }
  }
}

Expected behavior

GraphQL Code Generator should be able to parse query {..} strings inside of my .ts/.tsx files.

Environment:

  • OS: macOS
  • NodeJS: 8.12
  "dependencies": {
    "@graphql-codegen/cli": "^1.4.0",
    "@graphql-codegen/typescript": "^1.4.0",
    "@graphql-codegen/typescript-operations": "^1.4.0",
    "@types/graphql": "^14.2.3",
    "graphql": "^14.4.2",
    "graphql-tag": "^2.10.1",
    "typescript": "^3.5.3"
  }

Most helpful comment

Thank @brookback , I added docs for it.

All 3 comments

Hi @brookback !
We decided not to test each template literal string for GraphQL documents, because it might effect performance (trying to parse each found string).
You can either use a GraphQL tag library (such as gql from graphql-tag, or any other), or you can use magic comments (which also supported in most IDEs).

const USER_QUERY = /* GraphQL */`
    query UserQuery($userId: ID!) {
        user(_id: $userId) {
          name
        }
    }
`;

Thanks, prefixing with a comment works great for generating queries from a JS string!

Perhaps this can go into the documentation.

Thank @brookback , I added docs for it.

Was this page helpful?
0 / 5 - 0 ratings