Skip to content

hikiko4ern/swc-plugin-minify-graphql

Repository files navigation

swc-plugin-minify-graphql

GraphQL query and schema minimizer plugin for SWC

Compatibility

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 swc_core version
0.1 0.98.0 - *

Usage

Install the package:

npm i swc-plugin-minify-graphql

and add it to your SWC config.

Basic

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.

Template literals with expressions

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 tag support

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.

Credits