CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-graphql-tag

A JavaScript template literal tag that parses GraphQL queries into the standard GraphQL AST

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

GraphQL Tag

GraphQL Tag provides a JavaScript template literal tag that parses GraphQL queries into the standard GraphQL Abstract Syntax Tree (AST). It serves as a fundamental utility for GraphQL development, offering query parsing, fragment composition, and caching capabilities for maximum compatibility across GraphQL tooling ecosystems.

Package Information

  • Package Name: graphql-tag
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install graphql-tag
  • Peer Dependencies: graphql (^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0)

Core Imports

import gql from "graphql-tag";

CommonJS (backward compatible):

const gql = require("graphql-tag");

Named imports with utilities:

import { 
  gql, 
  resetCaches, 
  disableFragmentWarnings,
  enableExperimentalFragmentVariables,
  disableExperimentalFragmentVariables 
} from "graphql-tag";

Basic Usage

import gql from "graphql-tag";

// Basic query parsing
const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }
`;

// Fragment definition
const userFragment = gql`
  fragment User_user on User {
    firstName
    lastName
  }
`;

// Query with fragment composition
const queryWithFragment = gql`
  {
    user(id: 5) {
      ...User_user
    }
  }
  ${userFragment}
`;

Capabilities

GraphQL Query Parsing

Parses GraphQL query strings into the standard GraphQL AST using template literals or function calls.

/**
 * Parses GraphQL query strings into DocumentNode AST
 * @param literals - Template literal strings or single query string
 * @param args - Template literal arguments for fragment interpolation  
 * @returns Parsed GraphQL DocumentNode
 */
function gql(
  literals: string | readonly string[],
  ...args: any[]
): DocumentNode;

Usage Examples:

// Template literal tag usage
const query = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      name
      email
    }
  }
`;

// Function call usage  
const query = gql("{ user { name } }");

// Fragment interpolation
const userFields = gql`
  fragment UserFields on User {
    id
    name
    email
  }
`;

const query = gql`
  query GetUsers {
    users {
      ...UserFields
    }
  }
  ${userFields}
`;

Cache Management

Manage the internal parse result cache for performance optimization and testing.

/**
 * Clears the internal document cache and fragment source map
 * Useful for testing or memory management
 */
function resetCaches(): void;

Usage Example:

import { resetCaches } from "graphql-tag";

// Clear cache during tests
beforeEach(() => {
  resetCaches();
});

Fragment Warning Control

Control console warnings for duplicate fragment names across your application.

/**
 * Disables console warnings for duplicate fragment names
 * Recommended for production builds
 */
function disableFragmentWarnings(): void;

Usage Example:

import { disableFragmentWarnings } from "graphql-tag";

// Disable warnings in production
if (process.env.NODE_ENV === 'production') {
  disableFragmentWarnings();
}

Experimental Fragment Variables

Enable or disable experimental support for parameterized fragments.

/**
 * Enables experimental support for parameterized fragments
 * Allows fragments to accept variables like operations
 */
function enableExperimentalFragmentVariables(): void;

/**
 * Disables experimental fragment variables support
 * Returns to standard GraphQL fragment behavior
 */
function disableExperimentalFragmentVariables(): void;

Usage Example:

import { enableExperimentalFragmentVariables, gql } from "graphql-tag";

// Enable experimental feature
enableExperimentalFragmentVariables();

// Use parameterized fragment
const fragment = gql`
  fragment UserInfo($includeEmail: Boolean!) on User {
    name
    email @include(if: $includeEmail)
  }
`;

Webpack Loader Integration

The package includes a webpack loader for preprocessing GraphQL files at build time.

/**
 * Webpack loader configuration for .graphql/.gql files
 * Processes GraphQL files into JavaScript modules with parsed AST
 */
module.exports = {
  module: {
    rules: [
      {
        test: /\.(graphql|gql)$/,
        exclude: /node_modules/,
        loader: 'graphql-tag/loader'
      }
    ]
  }
};

File Import Usage:

// Import .graphql files as parsed DocumentNode
import MyQuery from './queries/MyQuery.graphql';

// Import named queries/fragments from single file
import { GetUsers, UserFragment } from './queries/users.graphql';

GraphQL File with Named Exports:

# users.graphql
query GetUsers {
  users {
    ...UserFragment
  }
}

fragment UserFragment on User {
  id
  name
  email
}

Types

/**
 * GraphQL DocumentNode representing parsed query/mutation/fragment
 * From the graphql package - standard GraphQL AST format
 */
interface DocumentNode {
  readonly kind: "Document";
  readonly definitions: ReadonlyArray<DefinitionNode>;
  readonly loc?: Location;
}

/**
 * Individual definition within a GraphQL document
 * Can be OperationDefinition or FragmentDefinition
 */
interface DefinitionNode {
  readonly kind: string;
  readonly loc?: Location;
}

/**
 * Location information for AST nodes
 * Contains source text and position details
 */
interface Location {
  readonly start: number;
  readonly end: number;
  readonly source: Source;
}

/**
 * Source text information from GraphQL parsing
 * Contains original GraphQL source and metadata
 */
interface Source {
  readonly body: string;
  readonly name?: string;
  readonly locationOffset: {
    readonly line: number;
    readonly column: number;
  };
}

Error Handling

The library throws standard JavaScript errors for invalid GraphQL:

  • Parse Errors: Invalid GraphQL syntax throws parsing errors from the underlying graphql library
  • Document Validation: Throws Error with message "Not a valid GraphQL document." for non-Document AST results
  • Loader Errors: Webpack loader throws errors for unnamed operations in multi-operation files

Performance Features

  • Parse Result Caching: Identical query strings are parsed once and cached using normalized string keys
  • Fragment Deduplication: Automatically removes duplicate fragments within documents
  • Build-time Optimization: Webpack loader enables compile-time parsing for faster runtime performance
  • Memory Efficiency: Location metadata can be stripped from AST for reduced memory usage

Framework Integration

GraphQL Tag integrates seamlessly with popular GraphQL clients:

  • Apollo Client: Primary recommended method for query definition
  • Relay: Compatible with Relay's GraphQL requirements
  • urql: Supported for query parsing and caching
  • graphql-request: Works with any client accepting DocumentNode
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/graphql-tag@2.12.x
Publish Source
CLI
Badge
tessl/npm-graphql-tag badge