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.
npm install graphql-tagVerified import paths — ran on the pinned version, not inferred.
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.
Ensure your project's `graphql` peer dependency is compatible with `graphql-tag` v2.12.6 and newer (i.e., `^15.0.0 || ^16.0.0`). Review your `graphql` schema and resolvers for any breaking changes introduced in `graphql` v16.
Install the `graphql` package: `npm install graphql` or `yarn add graphql`. Ensure its version satisfies the `graphql-tag` peer dependency range.
Always include both the GraphQL spread (`...FragmentName`) in the selection set and the JavaScript template literal placeholder (`${FragmentVariable}`) in the `gql` tag when defining documents that use fragments.Remove any usage of `disableFragmentWarnings`. If you encounter fragment warnings, ensure all defined fragments are either used or removed to maintain clean GraphQL documents.
Ensure the template literal passed to `gql` contains a syntactically valid GraphQL query, mutation, subscription, or fragment definition.
Verify that `gql` is imported as the default export: `import gql from 'graphql-tag';` for ESM, or `const gql = require('graphql-tag');` for CommonJS.Carefully 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.