Removes unnecessary white space from GraphQL queries using
graphql-query-compress
.
npm install --save-dev babel-plugin-transform-compress-graphql
Compress GraphQL queries by simply adding a /* GraphQL */
comment or tagging them with
the gql
template tag. The tag name or comment text can be customized with an option.
In
const query = gql`
people(uuid:"${uuid}") {
uuid,
fullName,
dateOfBirth,
nextBirthday,
age,
relations {
description,
type,
person {
uuid,
fullName
}
}
events {
uuid,
name,
description,
startDate, startTime,
endDate, endTime
}
}`;
Which is pretty big literal right?
Out
const query = `people(uuid:"${uuid}"){uuid,fullName,dateOfBirth,nextBirthday,age,relations{description,type,person{uuid,fullName}}events{uuid,name,description,startDate,startTime,endDate,endTime}}`;
Which saves quite some white space which has no use in production builds.
Since 1.3.0
it's possible to use a comment to mark a template literals as a GraphQL query.
const query = /* GraphQL */ `
people {
fullName,
age
}
`;
The value of the comment can be changed using the comment
option. The comment is being
matched in a case-insensitive manner so /* graphql */
is also fine.
Important: The comment only works with template literals. Normal strings will not be compressed.
.babelrc
{
"env": {
"production": {
"plugins": ["transform-compress-graphql"]
}
}
}
babel --plugins transform-compress-graphql script.js
require("@babel/core").transform("code", {
plugins: ["transform-compress-graphql"],
});
Options can be passed by wrapping the plugin name in an array and adding an object literal as the second item in that array.
For example in your .babelrc:
{
"env": {
"production": {
"plugins": [
[
"transform-compress-graphql",
{
"tagName": "gql",
"tagFunction": "",
"comment": "graphql",
"removeComments": true
}
]
]
}
}
}
The following options are available:
tagName
-String
with the name of the tag to search for. Defaults to"gql"
.tagFunction
-String
with the name of the tag to replace the tag with. Defaults to:""
which means the tag will be removed from the output.removeComments
-Boolean
when set tofalse
will leave any matched comments in place. Defaults totrue
.comment
-String
with the case-insensitive text matched in any leading comments for a template literal. The entire string will be expected. Defaults to"graphql"
.
For template literals with a tag named gql
(or with the same name as the tagName
option) the scope will be checked for an existing binding of that variable and will not
be replaced with tagFunction
if it exists.
GraphQL literals will be compressed with graphql-query-compress
.
Any issues related to the compressed query result should be posted as an issue in the
issue tracker of that package.
MIT