0

I created a .gql file for my query and I'm importing it like this:

const query = require("@/hello.gql");

However, if I log the query variable to the console, it shows an object, not a string. What can I do so that my imported query is just a string?

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
Lévi Simeon
  • 13
  • 1
  • 4

3 Answers3

3

When querying your server using apollo-client, the provided query parameter has to be an object of the type DocumentNode, which is an AST representation of the query. In other words, if you use apollo-client, you can't just pass it a query as a string, you have to parse it first. This is commonly done using the graphql-tag library. It can also be done automatically through webpack by utilizing a loader like graphql-tag's loader or graphql-loader. If you utilize a loader like that, then any .gql files you import will automatically be parsed into DocumentNode objects for you.

If you're not using apollo-client, there's no need to utilize those loaders. If you still want to store you queries in separate files and import them as strings, you should utilize a different loader, for example, raw-loader.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
0

Because, you are only importing the query, not using it.

You can use apollo to use that query like this

const yourQuery= require("@/hello.gql");

data(){
 return {
    queryResponse: []  
  }
}

apollo: {
    queryResponse: {
      prefetch: true,
      query: yourQuery
    }
  }

Whit this, you are fetch the query and save the response in queryResponse

Ignacio
  • 116
  • 4
0

Now raw-loader is deprecated, you can load them like this.

In the webpack config

 module: {
  rules: [
    {
      test: /\.gql/,
      type: "asset/source",
    },
  ],
},

Then import

import myGraphQlQuery from "myGraphQlQuery.gql"
  • If the "test" property is matching any .gql files other that the intended target, then there may be unintended consequences, depending on what OP is ultimately trying to achieve. – ryanwebjackson Apr 11 '22 at 14:37