Webpack loader
You can load GraphQL queries over .graphql
files using Webpack. The package @graphql-tools/webpack-loader
comes with a loader easy to setup and with some benefits:
- Do not process GraphQL ASTs on client-side
- Enable queries to be separated from logic
In the example below, we create a new file called currentUser.graphql
:
You can load this file adding a rule in your webpack config file:
As you can see, .graphql
or .gql
files will be parsed whenever imported:
#
Optional: Install and configure a custom Webpack configuration (when using Angular CLI)Install @angular-builders/custom-webpack
with the following command:
(Or alternative command when using yarn or another package-manager)
Then create a Webpack-configuration file webpack.config.js
in your application root containing your Webpack configuration (as listed above):
After that, create your type-definition for your .graphql
files, so TypeScript will transform them into importable objects with src/@types/graphql.d.ts
:
Next, update your TSConfig (tsconfig.json
):
Finally you have to manipulate your angular.json
to accept your customized Webpack configuration:
(Based on How to resolve import for the .graphql file with typescript and webpack)
#
JestJest can't use the Webpack loaders. To make the same transformation work in Jest, use @graphql-tools/jest-transform
.
#
FragmentsYou can use and include fragments in .graphql
files and have webpack include those dependencies for you, similar to how you would use fragments and queries with the gql tag in plain JS.
See how we import the UserInfo fragment from another .graphql
file (same way you'd import modules in JS).
And here's an example of defining the fragment in another .graphql
file.