4

I am working on project with teachnology combination of React + Postgraphile (GraphQL) + axios(http request to postgraphile server).

It has lots of GraphQL queries. Initially started with queries in same file with the other JavaScript and rendering code but it became messy as soon as specific queries has been added.

While searching I came to know that we can detach queries into separate files - .graphql or .gql For this to allow I have to integrate with Webpack module -

I wanted to know if there is simpler(kind of out of the box) way to achieve similar thing without using Webpack as it needs lots of configuration in place.

Any pointers or examples will be really helpful.

Thank you.

Manan
  • 140
  • 2
  • 14

3 Answers3

5

On the client, we typically create a mirrored tree of the pages directory under graphql then create js or ts files with the query exported! Then importing it where needed (in our case the graphql client request body).

So for example:

export const GET_TEAM_QUERY = `
  query {
    // your query here
  }
`

Hope that helps!

2

Since it's non-standard functionality to import/require a file that's not .js or .json, you need some kind of plugin to tell the runtime how to interpret it and not crash. The two ways I know of are:

module.exports = {
  // ...
  module: {
    rules: [
      // babel loader, css imports,
      {
        test: /\.(graphql|gql)$/,
        exclude: /node_modules/,
        loader: 'graphql-tag/loader'
      },
    ],
  },
  // ...
}

  • or, with babel-plugin-import-graphql in babel, though this plugin just mimcs the functionality of the above webpack loader, and in fact suggests using it along side graphql-tag to reduce the size of the compiled query. It is useful if you need to run your code with babel-node, but I would suggest the above webpack loader in most cases.
DanielFGray
  • 61
  • 1
  • 4
2

I found a very neat solution to this problem: graphql-code-generator. Using this tool, you can write your queries and fragments in separate files and it will compile them into typescript files, fully type-safe and ready to be imported into your components.

Naresh
  • 23,937
  • 33
  • 132
  • 204