Hi, I’m Mohsen ZareZardeyni, and I’m a software engineer at Sigma Telecom LLC.
At Sigma, for developing our back office application, we decided to use GraphQL, Typescript and Apollo server. We choose Schema first approach and stored our schema in separate .graphql
files. In order to import our schema within our Typescript code, we ended up using Webpack as our transpiler.
As I was looking for a way to do so, I didn’t find any good tutorial on this matter so I’m providing this tutorial for future researchers!🤠
First, you need to add the following configuration to your tsconfig.json
. This will tell Typescript to use the src/@types
folder in addition to node_modules/@types
in order to identify your types.
Then you need to introduce .graphql
files to Typescript. In order to do this, you need to create a graphql.d.ts
in your src/@types
folder. The following code will tell typescript every time it sees an imported file with the .graphql
extension, it will provide a GraphQL DocumentNode
, which is the type you need to provide for your GraphQL Schema.
In our case, we used apollo-server from Apollo Foundation, but any other GraphQL server library uses the same pattern. With previous steps, the following code will let you import your .graphql
files without any typing issue.
Finally, the last step is to tell webpack how to treat .graphql
imports. The following code will tell webpack
every time it sees a .graphql
file, it should use graphql-tag/loader
in order to load the content.
Hope this helps you:)
Top comments (10)
What advantages has using
.graphql
extension?Taken from the docs:
This link is about wepback with client
Ah right, didn't pay attention since I use it client-side. So only second point might apply in a server environment.
Thanks, clear & concise!
Also had to add
"allowSyntheticDefaultImports": true
to mytsconfig.json
.Hey, nice tutorial. FYI, your first 2 gists should be interchanged.
tsconfig.json
should be first &graphql.d.ts
should be second :)Thanks:)
Thanks for the tutorial, this helped me import graphql files to use with apollo server :)
Do you have any idea how to config swcrc?
I tried it, and it worked, but in vscode i do not get the benefit of auto import of the gql files. When i try to use the query file, i have no auto complete for it.