graphql-code-generator: Got a duplicate identifier issue

Describe the bug

The graphql codegen generate duplicate identifier. cf the codesandbox


export type NavigationItemsQueryVariables = Exact<{ [key: string]: never; }>;


export type NavigationItemsQuery = { __typename?: 'Query', homePage?: { __typename?: 'HomePage', id: string, navigation: Array<{ __typename?: 'NavigationItem', id: string, slug?: string | null, title?: string | null }> } | null };


      export interface PossibleTypesResultData {
        possibleTypes: {
          [key: string]: string[]
        }
      }
      const result: PossibleTypesResultData = {
  "possibleTypes": {
    "HomePageNavigationItems": [
      "NavigationItem"
    ],
    "Node": [
      "Article",
      "Asset",
      "FieldOfWork",
      "HomePage",
      "NavigationItem",
      "ScheduledOperation",
      "ScheduledRelease",
      "User"
    ],
    "ScheduledOperationAffectedDocument": [
      "Article",
      "Asset",
      "FieldOfWork",
      "HomePage",
      "NavigationItem"
    ]
  }
};
      export default result;
    
export type NavigationItemsQueryVariables = Exact<{ [key: string]: never; }>;


export type NavigationItemsQuery = { __typename?: 'Query', homePage?: { __typename?: 'HomePage', id: string, navigation: Array<{ __typename?: 'NavigationItem', id: string, slug?: string | null, title?: string | null }> } | null };

Your Example Website or App

https://stackblitz.com/edit/github-mvhfsr?file=graphql/generated/index.ts

Steps to Reproduce the Bug or Issue

  1. Run yarn codegen
  2. Check the graphql/generated/index.ts file

Expected behavior

No duplicate identifier

Screenshots or Videos

No response

Platform

  • OS: MacOS
  • NodeJS: v16.13.2
  • graphql 16.5.0
    "@graphql-codegen/cli": "2.9.1",
    "@graphql-codegen/fragment-matcher": "3.3.0",
    "@graphql-codegen/introspection": "2.2.0",
    "@graphql-codegen/typescript": "2.7.2",
    "@graphql-codegen/typescript-graphql-request": "^4.5.2",
    "@graphql-codegen/typescript-operations": "2.5.2",
    "@graphql-codegen/typescript-react-apollo": "3.3.2",
    "@types/node": "^18.0.6",
    "@types/react": "^18.0.15",

Codegen Config File

overwrite: true schema: “https://api-eu-central-1.hygraph.com/v2/cl335cxsw434p01z87rv1ba3t/master” documents: “graphql/queries/*.{ts,tsx,gql,graphql}” generates: ./graphql/generated/index.ts: plugins: - typescript - typescript-operations - fragment-matcher - typescript-operations - typescript-graphql-request config: namingConvention: enumValues: change-case-all#titleCase

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 11
  • Comments: 24 (2 by maintainers)

Most upvoted comments

@ardatan Thank you so much for the response! I’ll remove the client preset and see if that fixes it

Edit: It did! You’re amazing, thank you again!

For anyone who runs into this in the future, in codegen.ts I changed

generates: {
    'app/javascript/generated/graphql': {
      preset: 'client',
      plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
    },
  }

to

generates: {
  "app/javascript/generated/graphql.tsx": {
    plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
  },
}

@RomanBaiocco You get duplicate error because client preset is defined with plugins. You get validation error because you don’t have tsx extension as output in TS Config.

This issue won’t be reproducible with newer version of codegen that raises an error when plugins are listed along with preset: "client"

Still happening

@llanginger, you need to not have the following in your plugins array: typescript, typescript-operations and typescript-react-apollo. So you config should look like

const config = {
overwrite: true,
  schema: [
    {
      'myurl': {
        headers: {
          Authorization: "Bearer " + TOKEN,
          ["x-correlation-id"]: uuidv4()
        }
      }
    }
  ],
  documents: ['src/graphql/testQuery/*.{ts,tsx}'],
  generates: {
    './src/__generated__/': {
      preset: 'client',
      plugins: [
      // don't need to add plugins when using the client preset
       ],
      config: {
        withHooks: true,
        withComponent: false,
        futureProofEnums: true
      },
      presetConfig: {
        gqlTagName: 'gql',
        fragmentMasking: false,
      },
    },
  },
  ignoreNoDocuments: true,
}
export default config

I got the same issues with the following config:

ignoreNoDocuments: true, hooks: { afterAllFileWrite: ['prettier --write'] }, documents: ['src/graphql/data/**/*.ts'], schema: { [API_URL]: { headers: { 'key': API_KEY } } }, generates: { './src/graphql/codegen/': { preset: 'client', plugins: [], config: { useTypeImports: true, documentMode: 'string', namingConvention: 'keep' }, presetConfig: { fragmentMasking: { unmaskFunctionName: 'unmaskFragment' } }, documentTransforms: [addTypenameSelectionDocumentTransform] } }

The output is:

export type Explainers = { .... } export type Explainers = Explainers & { .... }

I solved it by adding namingConvention: ‘keep’ in the config and the second type is now:

export type explainers = Explainers & { ... }

I get the same issue coming from the typescript plugin

I was getting this error also and resolved it after trying futureProofEnums (thank you @luizakp!). In-case it is useful, our config looks a bit like this;

const config: CodegenConfig = {
  overwrite: true,
  schema: [
    {
      'https://graphql.datocms.com/': {
        headers: {
          // ... 
        },
      },
    },
  ],
  generates: {
    'src/generated/graphql.ts': {
      plugins: ['typescript'],
      config: {
        enumsAsTypes: true,
        futureProofEnums: true,
      },
    },
    './graphql.schema.json': {
      plugins: ['introspection'],
    },
  },
}

@llanginger, I misread your original post. Uhm, I think the preset will write to a directory, while the typescript-react-apollo wants to write to a file. So if you remove the preset, you have to change generates key to a file name instead of a directory, i.e. ./src/__generated__/ needs to become something like ./src/__generated__/generated-hooks.ts

@llanginger, I misread your original post. Uhm, I think the preset will write to a directory, while the typescript-react-apollo wants to write to a file. So if you remove the preset, you have to change generates key to a file name instead of a directory, i.e. ./src/__generated__/ needs to become something like ./src/__generated__/generated-hooks.ts

This approach does not allow to keep the preset features, because typescript-react-apollo writes the code dependent from the graphql.ts generated by the ‘client’ preset.

I want to keep the functionality of the preset (with fragment masking, gpl and index files) and I need an apollo plugin. So, is it possible?

@ardatan Thank you so much for the response! I’ll remove the client preset and see if that fixes it

Edit: It did! You’re amazing, thank you again!

For anyone who runs into this in the future, in codegen.ts I changed

generates: {
    'app/javascript/generated/graphql': {
      preset: 'client',
      plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
    },
  }

to

generates: {
  "app/javascript/generated/graphql.tsx": {
    plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
  },
}

But how u guys using without the preset: 'client',, her if i run without it in gives an error: Command failed with exit code 1.

Using futureProofEnums worked for me

I encountered the same issue here, with plugins typescript, typescript-operations and typescript-urql

The preset: “client” is not meant to be used in combination with other plugins. You must use either the client-preset or typescript-urql-plugin which provides 2 different ways to get typed GraphQL Operations.

https://stackoverflow.com/a/74137167/2690160

@Qonditive That worked, many thanks, my codegen.ts is quite complex but may help someone else as a reference:

import type { CodegenConfig } from "@graphql-codegen/cli"
+ import { addTypenameSelectionDocumentTransform } from "@graphql-codegen/client-preset"
import dotenv from "dotenv"

dotenv.config({ path: ".env.local" })

const config: CodegenConfig = {
  schema: process.env.DGRAPH_GRAPHQL_ENDPOINT,
  documents: [
    "db/operations/**/*.tsx",
    "db/operations/**/*.ts",
    "components/**/*.tsx",
    "components/**/*.ts",
  ],
  watch: true,
  ignoreNoDocuments: true,
+   hooks: {
+     afterAllFileWrite: ["prettier --write"],
+   },
  generates: {
    "./db/generated-graphql/": {
      preset: "client",
      presetConfig: {
        fragmentMasking: { unmaskFunctionName: "getFragmentData" },
      },
      config: {
+        useTypeImports: true,
        documentMode: "string",
+        namingConvention: "keep",
        scalars: {
          DateTime: "Date",
          Int64: "string",
        },
        defaultScalarType: "unknown",
        avoidOptionals: true,
        strictScalars: true,
      },
+      documentTransforms: [addTypenameSelectionDocumentTransform],
    },
    "./db/generated-graphql/types.ts": {
      plugins: ["typescript", "typescript-operations"],
      config: {
        enumsAsTypes: false,
        futureProofEnums: true,
        skipTypename: true,
        scalars: {
          DateTime: "Date",
          Int64: "string",
        },
        defaultScalarType: "unknown",
        avoidOptionals: true,
        strictScalars: true,
+        namingConvention: "keep",
      },
    },
    "./db/schema.graphql": {
      plugins: ["schema-ast"],
      config: {
        includeDirectives: true,
      },
    },
  },
}

export default config

Hmm, is the functionality to generate the hooks (useSomeQuery) available as part of the client preset? If so I completely missed that.

When I remove the plugins and make no other changes I lose these, which are the main thing I’m trying to achieve with the plugins:

/**
 * __useAllEventsQuery__
 *
 * To run a query within a React component, call `useAllEventsQuery` and pass it any options that fit your needs.
 * When your component renders, `useAllEventsQuery` returns an object from Apollo Client that contains loading, error, and data properties
 * you can use to render your UI.
 *
 * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
 *
 * @example
 * const { data, loading, error } = useAllEventsQuery({
 *   variables: {
 *      ...
 *   },
 * });
 */
export function useAllEventsQuery(baseOptions: Apollo.QueryHookOptions<AllEventsQuery, AllEventsQueryVariables>) {
        const options = {...defaultOptions, ...baseOptions}
        return Apollo.useQuery<AllEventsQuery, AllEventsQueryVariables>(AllEventsDocument, options);
      }
export function useAllEventsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AllEventsQuery, AllEventsQueryVariables>) {
          const options = {...defaultOptions, ...baseOptions}
          return Apollo.useLazyQuery<AllEventsQuery, AllEventsQueryVariables>(AllEventsDocument, options);
        }
export type AllEventsQueryHookResult = ReturnType<typeof useAllEventsQuery>;
export type AllEventsLazyQueryHookResult = ReturnType<typeof useAllEventsLazyQuery>;
export type AllEventsQueryResult = Apollo.QueryResult<AllEventsQuery, AllEventsQueryVariables>;

@RomanBaiocco You get duplicate error because client preset is defined with plugins. You get validation error because you don’t have tsx extension as output in TS Config.

This issue won’t be reproducible with newer version of codegen that raises an error when plugins are listed along with preset: "client"