What is graphql-tag?
The graphql-tag npm package is primarily used for parsing GraphQL queries and fragments into a standard GraphQL AST (Abstract Syntax Tree). It is commonly used in JavaScript or TypeScript projects that interact with a GraphQL server. The package provides a simple and efficient way to embed GraphQL queries within the code.
What are graphql-tag's main functionalities?
Parsing GraphQL queries
This feature allows developers to write GraphQL queries inside JavaScript or TypeScript files using template literals. The gql function parses the query string into a GraphQL AST, which can then be used with GraphQL clients like Apollo Client.
import gql from 'graphql-tag';
const MY_QUERY = gql`
query GetUserInfo($userId: ID!) {
user(id: $userId) {
id
name
email
}
}
`;
Parsing GraphQL fragments
This feature allows the definition of GraphQL fragments that can be reused across multiple queries or mutations. The gql function is used to parse the fragment, and it can be embedded within queries or mutations to avoid repetition of field definitions.
import gql from 'graphql-tag';
const USER_FRAGMENT = gql`
fragment UserFragment on User {
id
name
email
}
`;
const MY_QUERY = gql`
query GetUserInfo($userId: ID!) {
user(id: $userId) {
...UserFragment
}
}
${USER_FRAGMENT}
`;
Support for multiple operations in a single document
graphql-tag supports defining multiple operations, such as queries and mutations, within a single gql template literal. This can be useful for organizing related operations together in one place.
import gql from 'graphql-tag';
const MULTIPLE_OPERATIONS = gql`
query GetUserInfo($userId: ID!) {
user(id: $userId) {
id
name
}
}
mutation UpdateUserName($userId: ID!, $newName: String!) {
updateUser(id: $userId, name: $newName) {
id
name
}
}
`;
Other packages similar to graphql-tag
graphql
The 'graphql' package is the core JavaScript implementation of GraphQL itself. It includes functionality for parsing queries, but it's more general-purpose and lower-level compared to graphql-tag. It does not provide the same template literal syntax for embedding queries.
apollo-boost
Apollo Boost is a package that includes graphql-tag as one of its dependencies. It provides a zero-config way to start using Apollo Client. It's more of a complete solution for managing GraphQL state in applications, whereas graphql-tag is focused solely on parsing queries.
graphql.macro
graphql.macro provides similar functionality to graphql-tag but is designed to work with Create React App without ejecting. It allows you to load .graphql and .gql files at compile time, which graphql-tag does not do by default.
graphql-tag
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-js
.
gql
This is a template literal tag you can use to concisely write a GraphQL query that is parsed into the standard GraphQL AST:
import gql from 'graphql-tag';
const query = gql`
{
user(id: 5) {
firstName
lastName
}
}
`
console.log(query);
You can easily explore GraphQL ASTs on astexplorer.net.
This package is the way to pass queries into Apollo Client. If you're building a GraphQL client, you can use it too!
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.
Babel preprocessing
GraphQL queries can be compiled at build time using babel-plugin-graphql-tag. Pre-compiling queries decreases the script initialization time and reduces the bundle size by potentially removing the need for graphql-tag
at runtime.
TypeScript
Try this custom transformer to pre-compile your GraphQL queries in TypeScript: ts-transform-graphql-tag.
React Native, Next.js
Additionally, in certain situations, preprocessing queries via the webpack loader is not possible. babel-plugin-inline-import-graphql-ast will allow one to import 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 {
...
}
Create-React-App
create-react-app@2.0.0
will support the ability to preprocess queries using graphql-tag/loader
without the need to eject.
If you're using an older version of create-react-app
, check out react-app-rewire-inline-import-graphql-ast to preprocess queries without needing to eject.
Webpack preprocessing with graphql-tag/loader
This package also includes a webpack loader. There are many benefits over this approach, which saves GraphQL ASTs processing time on client-side and enable queries to be separated from script over .graphql
files.
loaders: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader'
}
]
then:
import query from './query.graphql';
console.log(query);
Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.
Support for multiple operations
With the webpack loader, you can also import operations by name:
In a file called query.gql
:
query MyQuery1 {
...
}
query MyQuery2 {
...
}
And in your JavaScript:
import { MyQuery1, MyQuery2 } from 'query.gql'
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()