GraphQL Tag
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
-
Error: Must provide document
cause Attempting to call `gql` with an empty string or a non-string value, or with a string that is not a valid GraphQL document structure.fixEnsure the template literal passed to `gql` contains a syntactically valid GraphQL query, mutation, subscription, or fragment definition. -
TypeError: Cannot read properties of undefined (reading 'kind') OR TypeError: query.definitions is not iterable
cause This often happens when `gql` is not correctly imported (e.g., `import { gql } from 'graphql-tag';` instead of `import gql from 'graphql-tag';`), leading to `gql` being undefined or not the expected function.fixVerify that `gql` is imported as the default export: `import gql from 'graphql-tag';` for ESM, or `const gql = require('graphql-tag');` for CommonJS. -
Syntax Error: Expected Name, found { OR Syntax Error: Expected Name, found '...' (for fragments)cause The GraphQL string within the `gql` template literal contains a syntax error according to the GraphQL specification.fixCarefully review your GraphQL query, mutation, or fragment string for typos, missing commas, incorrect field names, or improper syntax. Tools like `eslint-plugin-graphql` can help catch these errors statically.
Warnings
- breaking Version 2.12.6 updated `graphql-tag` to support `graphql` package version 16. While `graphql-tag` itself mostly adapts, this might introduce compatibility issues if your project depends on older `graphql` versions or specific features that changed between `graphql` 15 and 16.
- gotcha The `graphql` package is a peer dependency and must be explicitly installed alongside `graphql-tag`. Forgetting this will lead to runtime errors when `graphql-tag` attempts to parse queries.
- gotcha When using fragments, you must explicitly embed the fragment variable into the template literal (e.g., `${User_details}`) AND spread the fragment within the GraphQL selection set (e.g., `...User_details`). Omitting the template literal embedding will result in the fragment not being included in the final AST, even if it's spread.
- deprecated The `disableFragmentWarnings` named export was previously available but is now deprecated and removed. It was used to suppress warnings about unused fragments.
Install
-
npm install graphql-tag -
yarn add graphql-tag -
pnpm add graphql-tag
Imports
- gql
import { gql } from 'graphql-tag'; const gql = require('graphql-tag').gql;import gql from 'graphql-tag';
- resetCaches
import resetCaches from 'graphql-tag';
import { resetCaches } from 'graphql-tag'; - stripIgnoredCharacters
import stripIgnoredCharacters from 'graphql-tag';
import { stripIgnoredCharacters } from 'graphql-tag';
Quickstart
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);