Package detail

graphql-tag

apollographql30.7mMIT2.12.6

A JavaScript template literal tag that parses GraphQL queries

readme

graphql-tag

npm version Build Status Get on Slack

Helpful utilities for parsing GraphQL queries. Includes:

  • gql A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST.
  • /loader A webpack loader to preprocess queries

graphql-tag uses the reference graphql library under the hood as a peer dependency, so in addition to installing this module, you'll also have to install graphql.

gql

The gql template literal tag can be used to concisely write a GraphQL query that is parsed into a standard GraphQL AST. It is the recommended method for passing queries to Apollo Client. While it is primarily built for Apollo Client, it generates a generic GraphQL AST which can be used by any GraphQL client.

import gql from 'graphql-tag';

const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }
`

The above query now contains the following syntax tree.

{
  "kind": "Document",
  "definitions": [
    {
      "kind": "OperationDefinition",
      "operation": "query",
      "name": null,
      "variableDefinitions": null,
      "directives": [],
      "selectionSet": {
        "kind": "SelectionSet",
        "selections": [
          {
            "kind": "Field",
            "alias": null,
            "name": {
              "kind": "Name",
              "value": "user",
              ...
            }
          }
        ]
      }
    }
  ]
}

Fragments

The gql tag can also be used to define reusable fragments, which can easily be added to queries or other fragments.

import gql from 'graphql-tag';

const userFragment = gql`
  fragment User_user on User {
    firstName
    lastName
  }
`

The above userFragment document can be embedded in another document using a template literal placeholder.

const query = gql`
  {
    user(id: 5) {
      ...User_user
    }
  }
  ${userFragment}
`

Note: _While it may seem redundant to have to both embed the userFragment variable in the template literal AND spread the ...User_user fragment in the graphQL selection set, this requirement makes static analysis by tools such as eslint-plugin-graphql possible._

Why use this?

GraphQL strings are the right way to write queries in your code, because they can be statically analyzed using tools like eslint-plugin-graphql. However, strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff.

That's where this package comes in - it lets you write your queries with ES2015 template literals and compile them into an AST with the gql tag.

Caching parse results

This package only has one feature - it caches previous parse results in a simple dictionary. This means that if you call the tag on the same query multiple times, it doesn't waste time parsing it again. It also means you can use === to compare queries to check if they are identical.

Importing graphQL files

To add support for importing .graphql/.gql files, see Webpack loading and preprocessing below.

Given a file MyQuery.graphql

query MyQuery {
  ...
}

If you have configured the webpack graphql-tag/loader, you can import modules containing graphQL queries. The imported value will be the pre-built AST.

import MyQuery from 'query.graphql'

Importing queries by name

You can also import query and fragment documents by name.

query MyQuery1 {
  ...
}

query MyQuery2 {
  ...
}

And in your JavaScript:

import { MyQuery1, MyQuery2 } from 'query.graphql'

Preprocessing queries and fragments

Preprocessing GraphQL queries and fragments into ASTs at build time can greatly improve load times.

Babel preprocessing

GraphQL queries can be compiled at build time using babel-plugin-graphql-tag. Pre-compiling queries decreases script initialization time and reduces bundle sizes by potentially removing the need for graphql-tag at runtime.

TypeScript preprocessing

Try this custom transformer to pre-compile your GraphQL queries in TypeScript: ts-transform-graphql-tag.

React Native and Next.js preprocessing

Preprocessing queries via the webpack loader is not always possible. babel-plugin-import-graphql supports importing graphql files directly into your JavaScript by preprocessing GraphQL queries into ASTs at compile-time.

E.g.:

import myImportedQuery from './productsQuery.graphql'

class ProductsPage extends React.Component {
  ...
}

Webpack loading and preprocessing

Using the included graphql-tag/loader it is possible to maintain query logic that is separate from the rest of your application logic. With the loader configured, imported graphQL files will be converted to AST during the webpack build process.

Example webpack configuration

{
  ...
  loaders: [
    {
      test: /\.(graphql|gql)$/,
      exclude: /node_modules/,
      loader: 'graphql-tag/loader'
    }
  ],
  ...
}

Create React App

Preprocessing GraphQL imports is supported in create-react-app >= v2 using evenchange4/graphql.macro.

For create-react-app < v2, you'll either need to eject or use react-app-rewire-inline-import-graphql-ast.

Testing

Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.

Support for fragments

With the webpack loader, you can import fragments by name:

In a file called query.gql:

fragment MyFragment1 on MyType1 {
  ...
}

fragment MyFragment2 on MyType2 {
  ...
}

And in your JavaScript:

import { MyFragment1, MyFragment2 } from 'query.gql'

Note: If your fragment references other fragments, the resulting document will have multiple fragments in it. In this case you must still specify the fragment name when using the fragment. For example, with @apollo/client you would specify the fragmentName option when using the fragment for cache operations.

Warnings

This package will emit a warning if you have multiple fragments of the same name. You can disable this with:

import { disableFragmentWarnings } from 'graphql-tag';

disableFragmentWarnings()

Experimental Fragment Variables

This package exports an experimentalFragmentVariables flag that allows you to use experimental support for parameterized fragments.

You can enable / disable this with:

import { enableExperimentalFragmentVariables, disableExperimentalFragmentVariables } from 'graphql-tag';

Enabling this feature allows you declare documents of the form

fragment SomeFragment ($arg: String!) on SomeType {
  someField
}

Resources

You can easily generate and explore a GraphQL AST on astexplorer.net.

changelog

Change log

v2.12.6

  • Update peer dependencies to allow graphql ^16.0.0.
    @brainkim in #530

v2.12.5

  • Also publish src/ directory to npm, enabling source maps.
    @maclockard in #403

v2.12.4 (2021-04-29)

  • Allow fragments to be imported by name when using the webpack loader.
    @dobesv in #257

v2.12.3

  • Update tslib dependency to version 2.1.0.
    @benjamn in #381

v2.12.2

  • Avoid using Object.assign to attach extra properties to gql.
    @benjamn in #380

v2.12.1

  • To accommodate older versions of TypeScript, usage of the import type ... syntax (introduced by #325) has been removed, fixing issue #345.
    @benjamn in #352

v2.12.0

  • The graphql-tag repository has been converted to TypeScript, adding type safety and enabling both ECMAScript and CommonJS module exports. While these changes are intended to be as backwards-compatible as possible, we decided to bump the minor version to reflect the significant refactoring.
    @PowerKiKi and @benjamn in #325

v2.11.0 (2020-07-28)

  • package.json sideEffects changes to clearly identify that graphql-tag doesn't have side effects.
    @hwillson in #313

v2.10.4 (2020-07-08)

v2.10.3 (2020-02-05)

  • Further adjustments to the TS index.d.ts declaration file.
    @Guillaumez in #289

v2.10.2 (2020-02-04)

  • Update/fix the existing TS index.d.ts declaration file.
    @hwillson in #285

v2.10.1

  • Fix failures in IE11 by avoiding unsupported (by IE11) constructor arguments to Set by rocwang in #190

v2.10.0

v2.9.1

  • Fix IE11 support by using a regular for-loop by vitorbal in #176

v2.9.0

v2.8.0

  • Update graphql to ^0.13, support testing all compatible versions jnwng in PR #156
  • Export single queries as both default and named stonexer in PR #154

v2.7.{0,1,2,3}

  • Merge and then revert PR #141 due to errors being thrown

v2.6.1

  • Accept graphql@^0.12.0 as peerDependency jnwng addressing #134

v2.6.0

  • Support multiple query definitions when using Webpack loader jfaust in PR #122

v2.5.0

  • Update graphql to ^0.11.0, add graphql@^0.11.0 to peerDependencies pleunv in PR #124

v2.4.{1,2}

  • Temporarily reverting PR #99 to investigate issues with bundling

v2.4.0

v2.3.0

v2.2.2

v2.2.1

v2.2.0

v2.1.0

v2.0.0

Restore dependence on graphql module abhiaiyer91 in PR #46 addressing #6

v1.3.2

  • Add typescript definitions for the bundledPrinter PR #63

v1.3.1

  • Making sure not to log deprecation warnings for internal use of deprecated module jnwng addressing #54

v1.3.0

  • Bump bundled graphql packages to v0.9.1 jnwng in PR #55.
  • Deprecate the graphql/language/parser and graphql/language/printer exports jnwng in PR #55

v1.2.4

Restore Node < 6 compatibility. DragosRotaru in PR #41 addressing #39

v1.2.1

Fixed an issue with fragment imports. PR #35.

v1.2.0

Added ability to import other GraphQL documents with fragments using #import comments. PR #33

v1.1.2

Fix issue with interpolating undefined values Issue #19

v1.1.1

Added typescript definitions for the below.

v1.1.0

We now emit warnings if you use the same name for two different fragments.

You can disable this with:

import { disableFragmentWarnings } from 'graphql-tag';

disableFragmentWarnings();

v1.0.0

Releasing 0.1.17 as 1.0.0 in order to be explicit about Semantic Versioning.

v0.1.17

  • Allow embedding fragments inside document strings, as in
import gql from 'graphql-tag';

const fragment = gql`
  fragment Foo on Bar {
    field
  }
`;

const query = gql`
{
  ...Foo
}
${Foo}
`;

See also http://dev.apollodata.com/react/fragments.html

v0.1.16

  • Add caching to Webpack loader. PR #16

v0.1.15

  • Add Webpack loader to graphql-tag/loader.

v0.1.14

Changes were not tracked before this version.