GraphQL query and schema minimizer plugin for SWC
Since WASM plugins are not backward compatible (see swc-project/swc#5060, Selecting the version - SWC), use the table below to select the correct plugin version:
plugin version | used swc_core version |
potentially compatible swc_core versions |
---|---|---|
0.2 |
10.6.1 |
>=10 |
0.1 |
1.0.2 |
>=0.98.0 <10 |
Install the package:
npm i swc-plugin-minify-graphql
and add it to your SWC config.
The plugin handles string literals and template literals marked with the GraphQL comment
const QUERY = /* GraphQL */ `
query ($id: ID!) {
image (id: $id) {
...img
}
}
fragment img on Image {
id
url
}
`;
minifying them:
const QUERY = /* GraphQL */ `query($id:ID!){image(id:$id){...img}}fragment img on Image{id url}`;
Minification is supported not only for entire queries and schemas, but also for their individual parts (e.g., fragments):
const IMAGE_FIELDS = /* GraphQL */ `
id
url
`;
const IMAGE_FRAGMENT = /* GraphQL */ `
fragment image on Image {
id
url
}
`;
// becomes
const IMAGE_FIELDS = /* GraphQL */ `id url`;
const IMAGE_FRAGMENT = /* GraphQL */ `fragment image on Image{id url}`;
GraphQL comments are case-insensitive and can have any number of whitespace characters and asterisks at the beginning and end. /* graphql */
, /* GraphQL */
, /** GraphQL */
and even /* *** * gRaPhQl * *** */
will work.
Expressions within template literals are also supported:
const IMAGE = /* GraphQL */ `
id
url
`;
const ENTITY = /* GraphQL */ `
id
image {
${IMAGE}
previewUrl
}
`;
// becomes
const IMAGE = /* GraphQL */ `id url`;
const ENTITY = /* GraphQL */ `id image{${IMAGE} previewUrl}`;
But with a single exception: expressions cannot break GraphQL tokens. The following code is invalid:
const LONG = 'Long';
const FIELD = /* GraphQL */ `
id
some${LONG}FieldName
`;
// becomes
const FIELD = /* GraphQL */ `id some ${LONG} FieldName`;
// instead of
const FIELD = /* GraphQL */ `id some${LONG}FieldName`;
While the minified code may be correct in some cases, this usage is not intended and can be broken at any time.
gql
/graphql
tagged template literals are not currently supported, and there are no plans to add support. You can use other plugins like graphql-tag-swc-plugin
that support minification.
graphql-minify
: a re-implementation ofstripIgnoredCharacters
from the GraphQL.js reference implementation in Rust
Licensed under either of
- The Unlicense (UNLICENSE or https://unlicense.org/UNLICENSE)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.