Reputation: 150
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.
Upvotes: 4
Views: 5369
Reputation: 25763
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.
Upvotes: 2
Reputation: 81
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'
},
],
},
// ...
}
babel-node
, but I would suggest the above webpack loader in most cases.Upvotes: 2
Reputation: 111
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!
Upvotes: 5