UNPKG

7.94 kBMarkdownView Raw
1# graphql-tag
2[![npm version](https://badge.fury.io/js/graphql-tag.svg)](https://badge.fury.io/js/graphql-tag)
3[![Build Status](https://travis-ci.org/apollographql/graphql-tag.svg?branch=master)](https://travis-ci.org/apollographql/graphql-tag)
4[![Get on Slack](https://img.shields.io/badge/slack-join-orange.svg)](http://www.apollodata.com/#slack)
5
6Helpful utilities for parsing GraphQL queries. Includes:
7
8- `gql` A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST.
9- `/loader` A webpack loader to preprocess queries
10
11`graphql-tag` uses [the reference `graphql` library](https://github.com/graphql/graphql-js) under the hood as a peer dependency, so in addition to installing this module, you'll also have to install `graphql`.
12
13### gql
14
15The `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](https://github.com/apollographql/apollo-client). While it is primarily built for Apollo Client, it generates a generic GraphQL AST which can be used by any GraphQL client.
16
17```js
18import gql from 'graphql-tag';
19
20const query = gql`
21 {
22 user(id: 5) {
23 firstName
24 lastName
25 }
26 }
27`
28```
29
30The above query now contains the following syntax tree.
31
32```js
33{
34 "kind": "Document",
35 "definitions": [
36 {
37 "kind": "OperationDefinition",
38 "operation": "query",
39 "name": null,
40 "variableDefinitions": null,
41 "directives": [],
42 "selectionSet": {
43 "kind": "SelectionSet",
44 "selections": [
45 {
46 "kind": "Field",
47 "alias": null,
48 "name": {
49 "kind": "Name",
50 "value": "user",
51 ...
52 }
53 }
54 ]
55 }
56 }
57 ]
58}
59```
60
61#### Fragments
62
63The `gql` tag can also be used to define reusable fragments, which can easily be added to queries or other fragments.
64
65```js
66import gql from 'graphql-tag';
67
68const userFragment = gql`
69 fragment User_user on User {
70 firstName
71 lastName
72 }
73`
74```
75
76The above `userFragment` document can be embedded in another document using a template literal placeholder.
77
78```js
79const query = gql`
80 {
81 user(id: 5) {
82 ...User_user
83 }
84 }
85 ${userFragment}
86`
87```
88
89**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._
90
91#### Why use this?
92
93GraphQL strings are the right way to write queries in your code, because they can be statically analyzed using tools like [eslint-plugin-graphql](https://github.com/apollographql/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.
94
95That's where this package comes in - it lets you write your queries with [ES2015 template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) and compile them into an AST with the `gql` tag.
96
97#### Caching parse results
98
99This 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.
100
101
102### Importing graphQL files
103
104_To add support for importing `.graphql`/`.gql` files, see [Webpack loading and preprocessing](#webpack-loading-and-preprocessing) below._
105
106Given a file `MyQuery.graphql`
107
108```graphql
109query MyQuery {
110 ...
111}
112```
113
114If you have configured [the webpack graphql-tag/loader](#webpack-loading-and-preprocessing), you can import modules containing graphQL queries. The imported value will be the pre-built AST.
115
116```js
117import MyQuery from 'query.graphql'
118```
119
120#### Importing queries by name
121
122You can also import query and fragment documents by name.
123
124```graphql
125query MyQuery1 {
126 ...
127}
128
129query MyQuery2 {
130 ...
131}
132```
133
134And in your JavaScript:
135
136```javascript
137import { MyQuery1, MyQuery2 } from 'query.graphql'
138```
139
140### Preprocessing queries and fragments
141
142Preprocessing GraphQL queries and fragments into ASTs at build time can greatly improve load times.
143
144#### Babel preprocessing
145
146GraphQL queries can be compiled at build time using [babel-plugin-graphql-tag](https://github.com/gajus/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.
147
148#### TypeScript preprocessing
149
150Try this custom transformer to pre-compile your GraphQL queries in TypeScript: [ts-transform-graphql-tag](https://github.com/firede/ts-transform-graphql-tag).
151
152#### React Native and Next.js preprocessing
153
154Preprocessing queries via the webpack loader is not always possible. [babel-plugin-import-graphql](https://www.npmjs.com/package/babel-plugin-import-graphql) supports importing graphql files directly into your JavaScript by preprocessing GraphQL queries into ASTs at compile-time.
155
156E.g.:
157
158```javascript
159import myImportedQuery from './productsQuery.graphql'
160
161class ProductsPage extends React.Component {
162 ...
163}
164```
165
166#### Webpack loading and preprocessing
167
168Using 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.
169
170_**Example webpack configuration**_
171
172```js
173{
174 ...
175 loaders: [
176 {
177 test: /\.(graphql|gql)$/,
178 exclude: /node_modules/,
179 loader: 'graphql-tag/loader'
180 }
181 ],
182 ...
183}
184```
185
186#### Create React App
187
188Preprocessing GraphQL imports is supported in **create-react-app** >= v2 using [evenchange4/graphql.macro](https://github.com/evenchange4/graphql.macro).
189
190For **create-react-app** < v2, you'll either need to eject or use [react-app-rewire-inline-import-graphql-ast](https://www.npmjs.com/package/react-app-rewire-inline-import-graphql-ast).
191
192#### Testing
193
194Testing environments that don't support Webpack require additional configuration. For [Jest](https://facebook.github.io/jest/) use [jest-transform-graphql](https://github.com/remind101/jest-transform-graphql).
195
196#### Support for fragments
197
198With the webpack loader, you can import fragments by name:
199
200In a file called `query.gql`:
201
202```graphql
203fragment MyFragment1 on MyType1 {
204 ...
205}
206
207fragment MyFragment2 on MyType2 {
208 ...
209}
210```
211
212And in your JavaScript:
213
214```javascript
215import { MyFragment1, MyFragment2 } from 'query.gql'
216```
217
218Note: If your fragment references other fragments, the resulting document will
219have 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.
220
221### Warnings
222
223This package will emit a warning if you have multiple fragments of the same name. You can disable this with:
224
225```js
226import { disableFragmentWarnings } from 'graphql-tag';
227
228disableFragmentWarnings()
229```
230
231### Experimental Fragment Variables
232
233This package exports an `experimentalFragmentVariables` flag that allows you to use experimental support for [parameterized fragments](https://github.com/facebook/graphql/issues/204).
234
235You can enable / disable this with:
236
237```js
238import { enableExperimentalFragmentVariables, disableExperimentalFragmentVariables } from 'graphql-tag';
239```
240
241Enabling this feature allows you declare documents of the form
242
243```graphql
244fragment SomeFragment ($arg: String!) on SomeType {
245 someField
246}
247```
248
249### Resources
250
251You can easily generate and explore a GraphQL AST on [astexplorer.net](https://astexplorer.net/#/drYr8X1rnP/1).
252
\No newline at end of file