Подписаться на блог

How to fix unknown fragments types in graphql-codegen?

I spent half of the day setting up graphql-codegen to generate the correct types for fragment queries.

At first, my code looked like this:

// file1
export const DIALOG_FIELDS = gql(`
  fragment DialogFields on Dialog {
    id
    name
  }
`);

// file2
export const GET_DIALOG = gql(`
  ${DIALOG_FIELDS}
  query GetDialog($dialogId: ID!) {
    dialog(id: $dialogId) {
      ...DialogFields
    }
  }
`);
const config: CodegenConfig = {
  schema: CONFIG.apiHost,
  documents: ['src/**/*.{tsx,ts,js,jsx}', '!src/gql/__generated__/*.ts'],
  generates: {
    './src/gql/__generated__/': {
      preset: 'client',
      plugins: [],
      overwrite: true,
      presetConfig: {
        gqlTagName: 'gql'
      }
    }
  },
};

So, with the basic config I did get an unknown type for both the query and the fragment:

I found a simple solution for this — we need to remove the string interpolation for the fragment literal from the query, because graphql-codegen automatically includes fragments.

export const GET_DIALOG = gql(`
  query GetDialog($dialogId: ID!) {
    dialog(id: $dialogId) {
      ...DialogFields
    }
  }
`);

As a result, I did get an not unknown type, but the type with no data from the fragment for the query fragment.

I lost the most time at this stage, eventually finding a solution in the small GitHub thread. We need to disable fragment masking feature.

const config: CodegenConfig = {
  schema: CONFIG.apiHost,
  documents: ['src/**/*.{tsx,ts,js,jsx}', '!src/gql/__generated__/*.ts'],
  generates: {
    './src/gql/__generated__/': {
      preset: 'client',
      plugins: [],
      overwrite: true,
      presetConfig: {
        gqlTagName: 'gql',
        fragmentMasking: false
      }
    }
  },
};

Finally the type contains all the information and it is complete!

3 комментария
Adil 2023

Hello,

I was facing the same issue but could not find any solution for a long time. Then I found your blog post, followed the instructions, and now my issue is resolved.

THANK YOU SO MUCH!

Have a great day :D

Игорь Федюкин 2023

Ur welcome :D

Vitor 2023

Life saver!

Игорь Федюкин 2023

I’m glad to hear that 🙏

Josh 2023

TY dude! U saved my project pitch :D