How to share GraphQL codegen generated fragments across multiple projects?

226 views Asked by At

We use GraphQL codegen to generate our GQL client with preset and inlined GQL in our (React) components, as described in the article https://the-guild.dev/blog/unleash-the-power-of-fragments-with-graphql-codegen and so far, it is working great.

To reuse our code, we are building a common/shared components library so that our final apps can keep consistent UI and behavior, so we have the following structure:

  • common-lib with components and their query fragments, codegen is installed in this project.
  • app-1 with custom app-1 components and their query fragments, and top components that uses all of the query fragments to perform only one GQL query.
  • app-2 with custom app-2 components and their query fragments, and top components that uses all of the query fragments to perform only one GQL query.
  • etc...

We want to be able to use components from common-lib inside app-1, so our top components must be able to use fragments from common-lib, but of course, actually, codegen crashes because it does not know anything about these fragments (since these fragments have been processed by the common-lib codegen and not the app-1 codegen).

What is the best practice to handle this case?

Is there a way to register already generated fragments (from our common-lib) inside the codegen configuration of our final apps ?

A first simplistic approach, maybe not the best, could be to just read the files inside our common-lib by including them:

In our codegen config:

documents:
  - ./src/**/*.tsx
  - ./node_modules/common-lib/dist/**/*.js

Although it does not work, most likely because of the transpilation:

const test = graphql(`
  fragment TestObject on objects {
    id
  }
`);

then becomes:

const gql_1 = require("../generated/gql");
const test = (0, gql_1.graphql)(`
  fragment TestObject on objects {
    id
  }
`);

Is there a simple way to make the transpiled version work with the codegen?

Thank you in advance.

1

There are 1 answers

0
sjahan On

We solved the problem by using the simplistic approach mentionned in the question, with the detail that our modules are now transpiled to ESM and not to CJS anymore.

The produced code looks more like the original and the codegen is able to reread it successfully!