GraphQL Tag

2.12.6 · active · verified Sun Apr 19

graphql-tag is a JavaScript utility library that provides a template literal tag, `gql`, for parsing GraphQL query strings into the standard GraphQL Abstract Syntax Tree (AST). It is currently stable at version 2.12.6 and receives regular maintenance updates, including recent upgrades to support GraphQL 16. The library's primary function is to simplify the creation of GraphQL documents in application code, making them easily consumable by GraphQL clients like Apollo Client. A key differentiator is its built-in caching mechanism, which prevents redundant parsing of identical query strings and enables strict equality checks (`===`) between parsed query objects. It also includes a Webpack loader to allow direct importing of `.graphql` or `.gql` files, converting them into ASTs at build time. While it's particularly useful for static analysis tools like `eslint-plugin-graphql`, developers must explicitly embed fragment definitions within template literals even when spreading them to facilitate this analysis. It relies on the core `graphql` library as a peer dependency for its parsing capabilities.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define GraphQL queries and fragments using the `gql` template literal tag, including how to embed fragments for reuse and static analysis, producing a standard GraphQL AST.

import gql from 'graphql-tag';

// Define a reusable fragment
const UserFragment = gql`
  fragment User_details on User {
    id
    firstName
    lastName
  }
`;

// Embed the fragment in a query and export the final document
const GetUserQuery = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      ...User_details
    }
  }
  ${UserFragment} // Crucial for static analysis and fragment inclusion
`;

// Example of using the parsed query (e.g., with Apollo Client)
// console.log(GetUserQuery);

// You can also define mutations or subscriptions similarly
const CreateUserMutation = gql`
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) {
      ...User_details
    }
  }
  ${UserFragment}
`;

console.log('Parsed Query Document:', GetUserQuery);
console.log('Parsed Mutation Document:', CreateUserMutation);

view raw JSON →