nitrogql logonitrogql

nitrogql 1.4 release: Maybe the first step towards Fragment Colocation?

Published at December 9, 2023

Today, we are happy to announce release of nitrogql 1.4!

nitrogql is a toolchain for using GraphQL in TypeScript projects. In 1.4, we added support for importing fragments from other GraphQL documents. Previously you had to define all fragments in the same document as the operation that uses them.

The #import syntax

nitrogql 1.4 introduces a new syntax for importing fragments from other GraphQL documents. It looks like this:

#import Fragment1, Fragment2 from "./path/to/file.graphql"

Above is an example of importing two fragments from path/to/file.graphql (relative to the current file). The fragments are then available for use in the current document. Of course, the imported document must define these fragments.

You can also import all fragments from a document by using the * wildcard:

#import * from "./path/to/file.graphql"

This will import all fragments from path/to/file.graphql.

While the new syntax isn't part of the GraphQL specification, it is inspired by The Guild's similar syntax. Some of you may already be familiar with it.

Implications of the new syntax

Placing fragments in separate files is often done in the context of Fragment Colocation. Fragment Colocation is a practice where fragments are placed near (often in the same directory as) the component that uses them. One GraphQL query is prepared per page and it collects all fragments that are necessary for the component to render.

The addition of the #import syntax enables this use case for nitrogql users.

However, this is only the first step towards Fragment Colocation. Literature on Fragment Colocation often mentions that fragments be given an opaque type in operation results and that users can obtain actual contents by using a special function (e.g. useFragment).

The current version of nitrogql does not support this use case. We may add support for it in the future if there is demand for it.

For now, we hope that the new #import syntax will make your GraphQL development experience a bit better. Working examples of how to use the syntax are available in the examples directory.

Conclusion

In this release, we added support for importing fragments from other GraphQL documents. This is a step towards enabling Fragment Colocation.


nitrogql is developed by uhyo. Contribution is more than welcome!