graphql-tag vs graphql-tools vs optics-ts vs graphql-codegen
GraphQL Development Tools
graphql-taggraphql-toolsoptics-tsgraphql-codegenSimilar Packages:
GraphQL Development Tools

GraphQL Development Tools are libraries and utilities that assist developers in building, managing, and optimizing GraphQL APIs. These tools provide functionalities such as schema generation, type safety, query optimization, and more, making the development process more efficient and reliable. They help in automating repetitive tasks, ensuring better code quality, and enhancing the overall developer experience when working with GraphQL. graphql-codegen is a tool that generates TypeScript types, React hooks, and other artifacts from your GraphQL schema and queries, ensuring type safety and reducing manual coding. graphql-tag is a small library that allows you to write GraphQL queries using template literals, making it easier to embed queries directly in your JavaScript or TypeScript code. graphql-tools is a set of utilities for building and manipulating GraphQL schemas, including schema stitching, type merging, and creating mock servers, which helps in developing and testing GraphQL APIs more effectively. optics-ts is a library for tracking and analyzing GraphQL query performance and usage, providing insights into query execution times, frequency, and other metrics to help optimize your GraphQL API and improve its efficiency.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
graphql-tag9,093,2872,339-1004 years agoMIT
graphql-tools799,2745,4162.61 kB15811 days agoMIT
optics-ts241,887890137 kB212 years agoMIT
graphql-codegen16,6823,043-367-MIT
Feature Comparison: graphql-tag vs graphql-tools vs optics-ts vs graphql-codegen

Type Safety

  • graphql-tag:

    graphql-tag does not provide type safety on its own, but it works well with tools like graphql-codegen to generate types from the queries you define using its template literals.

  • graphql-tools:

    graphql-tools does not focus on type safety, but it allows you to define and manipulate your GraphQL schema in a type-safe manner if used with TypeScript.

  • optics-ts:

    optics-ts is designed for type-safe query analysis and performance tracking, providing a type-safe API for instrumenting and analyzing your GraphQL queries.

  • graphql-codegen:

    graphql-codegen generates TypeScript types based on your GraphQL schema and queries, ensuring type safety throughout your application and reducing the risk of runtime errors.

Query Embedding

  • graphql-tag:

    graphql-tag allows you to embed GraphQL queries directly in your code using template literals, making it easy to define and reuse queries in a readable format.

  • graphql-tools:

    graphql-tools does not handle query embedding, as it focuses on schema creation and manipulation rather than query definition.

  • optics-ts:

    optics-ts does not embed queries; it analyzes queries at runtime to provide performance insights and metrics.

  • graphql-codegen:

    graphql-codegen does not embed queries directly; instead, it generates code based on the queries you provide, which can be defined anywhere in your codebase.

Schema Manipulation

  • graphql-tag:

    graphql-tag does not manipulate the schema; it simply provides a way to define queries and fragments in a declarative manner.

  • graphql-tools:

    graphql-tools provides extensive utilities for schema manipulation, including merging multiple schemas, stitching them together, and creating mock implementations for testing.

  • optics-ts:

    optics-ts does not manipulate the schema; it works with the existing schema to analyze query performance and usage patterns.

  • graphql-codegen:

    graphql-codegen does not manipulate the schema; it reads the schema to generate types and other artifacts.

Performance Optimization

  • graphql-tag:

    graphql-tag has a minimal impact on performance when embedding queries, but it does not provide any optimization features for query execution.

  • graphql-tools:

    graphql-tools can help optimize schema design by allowing you to create more efficient schemas through stitching and merging, but it does not provide runtime performance optimization.

  • optics-ts:

    optics-ts helps optimize your GraphQL API by providing insights into query performance, allowing you to identify and address slow or inefficient queries.

  • graphql-codegen:

    graphql-codegen optimizes the development process by generating code automatically, but it does not optimize query performance at runtime.

Ease of Use: Code Examples

  • graphql-tag:

    Query embedding with graphql-tag

    import { gql } from 'graphql-tag';
    const GET_USERS = gql`
      query GetUsers {
        users {
          id
          name
        }
      }
    `;
    
  • graphql-tools:

    Schema stitching with graphql-tools

    import { mergeSchemas } from '@graphql-tools/schema';
    const schema1 = makeExecutableSchema({ typeDefs, resolvers });
    const schema2 = makeExecutableSchema({ typeDefs, resolvers });
    const mergedSchema = mergeSchemas({ schemas: [schema1, schema2] });
    
  • optics-ts:

    Performance tracking with optics-ts

    import { createOpticsLink } from 'optics-ts';
    const link = createOpticsLink({
      url: '/graphql',
      client: myGraphQLClient,
    });
    
  • graphql-codegen:

    TypeScript types generation with graphql-codegen

    documents: './src/**/*.graphql'
    config:
      scalars:
        Date: string
        JSON: any
    plugins:
      - typescript
      - typescript-resolvers
    
How to Choose: graphql-tag vs graphql-tools vs optics-ts vs graphql-codegen
  • graphql-tag:

    Choose graphql-tag if you need a lightweight solution for embedding GraphQL queries in your JavaScript or TypeScript code using template literals, making your queries more readable and maintainable.

  • graphql-tools:

    Choose graphql-tools if you are building complex GraphQL schemas and need utilities for schema stitching, type merging, and creating mock servers, which can help in developing and testing your API more effectively.

  • optics-ts:

    Choose optics-ts if you want to gain insights into your GraphQL query performance and usage, helping you identify slow queries and optimize your API for better efficiency.

  • graphql-codegen:

    Choose graphql-codegen if you want to automate the generation of TypeScript types and other artifacts from your GraphQL schema and queries, ensuring 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.