graphql-tag vs graphql-tools vs optics-ts vs graphql-codegen
GraphQL Utility Libraries Comparison
1 Year
graphql-taggraphql-toolsoptics-tsgraphql-codegenSimilar Packages:
What's GraphQL Utility Libraries?

These packages enhance the development experience when working with GraphQL by providing tools for code generation, query parsing, schema manipulation, and performance monitoring. They streamline the process of building, managing, and optimizing GraphQL APIs, making it easier for developers to create robust applications while ensuring type safety and performance efficiency.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
graphql-tag6,959,6492,332-1003 years agoMIT
graphql-tools696,3825,3792.73 kB1652 days agoMIT
optics-ts165,634829137 kB192 years agoMIT
graphql-codegen12,8403,040-382-MIT
Feature Comparison: graphql-tag vs graphql-tools vs optics-ts vs graphql-codegen

Code Generation

  • graphql-tag:

    graphql-tag does not provide code generation features but allows you to define and parse queries in a concise manner, which can complement code generation tools by ensuring queries are correctly formatted.

  • graphql-tools:

    graphql-tools focuses on schema definition and manipulation rather than code generation, allowing developers to create and modify schemas programmatically, which can be useful in dynamic environments.

  • optics-ts:

    optics-ts does not offer code generation capabilities but provides performance monitoring tools that can help identify issues in your GraphQL queries, enhancing overall application performance.

  • graphql-codegen:

    graphql-codegen automates the generation of TypeScript types and resolvers based on your GraphQL schema, significantly reducing the manual effort required to maintain type safety across your application.

Schema Management

  • graphql-tag:

    graphql-tag is primarily for query parsing and does not handle schema management, focusing instead on the client-side aspect of GraphQL queries.

  • graphql-tools:

    graphql-tools excels in schema management, allowing developers to create, merge, and manipulate schemas easily, making it ideal for complex applications with multiple schemas.

  • optics-ts:

    optics-ts does not manage schemas but provides insights into how schemas perform under load, helping developers optimize their GraphQL APIs.

  • graphql-codegen:

    graphql-codegen does not directly manage schemas but generates types based on existing schemas, ensuring that your application stays in sync with your GraphQL API.

Performance Monitoring

  • graphql-tag:

    graphql-tag does not include performance monitoring capabilities; its focus is on simplifying query management for clients.

  • graphql-tools:

    graphql-tools does not offer performance monitoring but provides tools for creating efficient resolvers and schema definitions, which can indirectly improve performance.

  • optics-ts:

    optics-ts is specifically designed for performance monitoring, allowing developers to track the execution time of queries and mutations, helping to identify performance bottlenecks.

  • graphql-codegen:

    graphql-codegen does not provide performance monitoring features but ensures that the generated code is optimized for type safety and maintainability.

Learning Curve

  • graphql-tag:

    graphql-tag is easy to learn, especially for developers already familiar with GraphQL, as it simplifies the process of defining and using queries in client applications.

  • graphql-tools:

    graphql-tools may have a steeper learning curve due to its extensive features for schema manipulation, but it is well-documented and provides powerful capabilities for advanced users.

  • optics-ts:

    optics-ts has a moderate learning curve, as understanding performance monitoring concepts is essential, but it offers clear documentation to help developers get started.

  • graphql-codegen:

    graphql-codegen has a moderate learning curve, especially for those unfamiliar with code generation tools, but its documentation and examples make it accessible for most developers.

Extensibility

  • graphql-tag:

    graphql-tag is not designed for extensibility; it serves a specific purpose of query parsing and does not support plugin architecture.

  • graphql-tools:

    graphql-tools is extensible, enabling developers to create custom schema directives and resolvers, which can enhance the functionality of their GraphQL APIs.

  • optics-ts:

    optics-ts is somewhat extensible, allowing integration with other monitoring tools, but it primarily focuses on performance insights specific to GraphQL.

  • graphql-codegen:

    graphql-codegen is highly extensible, allowing developers to create custom plugins to generate additional artifacts or modify the code generation process to fit their needs.

How to Choose: graphql-tag vs graphql-tools vs optics-ts vs graphql-codegen
  • graphql-tag:

    Opt for graphql-tag if you need a simple way to parse GraphQL queries into a format that can be used by Apollo Client or other GraphQL clients, making it easier to manage queries in your application.

  • graphql-tools:

    Select graphql-tools if you require advanced schema manipulation capabilities, such as merging schemas, creating mock data, or defining custom resolvers, which can be particularly useful in complex applications.

  • optics-ts:

    Use optics-ts if you want to monitor and analyze the performance of your GraphQL operations, providing insights into query execution times and helping to identify bottlenecks in your API.

  • graphql-codegen:

    Choose graphql-codegen if you want to automate the generation of TypeScript types, resolvers, and other artifacts from your GraphQL schema, enhancing type safety and reducing boilerplate code.

README for graphql-tag

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.