You are viewing documentation for a previous version of this software.

Switch to the latest stable version.

Loading queries with Webpack


You can load GraphQL queries over .graphql files using Webpack. The package graphql-tag comes with a loader easy to setup and with some benefits:

  1. Do not process GraphQL ASTs on client-side

  2. Enable queries to be separated from logic

In the example below, we create a new file called currentUser.graphql:

GraphQL
1query CurrentUserForLayout {
2  currentUser {
3    login
4    avatar_url
5  }
6}

You can load this file adding a rule in your webpack config file:

JavaScript
1module: {
2  rules: [
3    {
4      test: /\.(graphql|gql)$/,
5      exclude: /node_modules/,
6      loader: 'graphql-tag/loader',
7    },
8  ],
9},

As you can see, .graphql or .gql files will be parsed whenever imported:

JavaScript
1import React, { Component } from 'react';
2import { graphql } from '@apollo/react-hoc';
3import currentUserQuery from './currentUser.graphql';
4
5class Profile extends Component { ... }
6Profile.propTypes = { ... };
7
8export default graphql(currentUserQuery)(Profile)

Jest

Jest can't use the Webpack loaders. To make the same transformation work in Jest, use jest-transform-graphql.

FuseBox

FuseBox can't use the Webpack loaders. To make the same transformation work in FuseBox, use fuse-box-graphql-plugin.

React native

React native can't use the Webpack loaders. To make the same transformation work in React native, use babel-plugin-import-graphql.

Create-React-App

create-react-app can't use the Webpack loaders unless ejected. To make the same transformation work in create-react-app without ejecting, use graphql.macro.

JavaScript
1import { loader } from 'graphql.macro';
2const currentUserQuery = loader('./currentUser.graphql');

Fragments

You 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.

GraphQL
1#import "./UserInfoFragment.graphql"
2
3query CurrentUserForLayout {
4  currentUser {
5    ...UserInfo
6  }
7}

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.

GraphQL
1fragment UserInfo on User {
2  login
3  avatar_url
4}
Feedback

Edit on GitHub

Forums