TypeScript
graphql-files-modules

TypeScript GraphQL Files Modules

Package nameWeekly DownloadsVersionLicenseUpdated
@graphql-codegen/typescript-graphql-files-modules (opens in a new tab)DownloadsVersionLicenseMay 26th, 2023

Installation

Terminal
yarn add -D @graphql-codegen/typescript-graphql-files-modules
💡

Webpack Integration

If you wish to have a simpler integration in a Webpack project, use graphql-let (opens in a new tab), it uses this plugin behind the scenes, and provides simpler developer experience.

Pre-Requirements

To use this template, make sure you are using graphql-tag/loader (opens in a new tab) with Webpack.

This plugin generates TypeScript typings for .graphql files containing GraphQL documents, which later on can be consumed using graphql-tag/loader (opens in a new tab) or use string types if you will use the operations as raw strings, and get type-check and type-safety for your imports. This means that any time you import objects from .graphql files, your IDE will provide auto-complete.

This plugin also handles .graphql files containing multiple GraphQL documents, and name the imports according to the operation name.

⚠ Fragments are not generated with named imports, only as default imports, due to graphql-tag/loader behavior.

Config API Reference

modulePathPrefix

type: string default: (empty)

Allows specifying a module definition path prefix to provide distinction between generated types.

Usage Examples

generates: src/api/user-service/queries.d.ts
 documents: src/api/user-service/queries.graphql
 plugins:
   - typescript-graphql-files-modules
 config:
   # resulting module definition path glob: "*\/api/user-service/queries.graphql"
   modulePathPrefix: "/api/user-service/"

relativeToCwd

type: boolean default: false

By default, only the filename is being used to generate TS module declarations. Setting this to true will generate it with a full path based on the CWD.

prefix

type: string default: *\/

By default, a wildcard is being added as prefix, you can change that to a custom prefix

type

type: string (values: DocumentNode, string) default: DocumentNode

By default, the named exports will have a type DocumentNode. Change this to "string" if you only use raw strings.

Example

Given that you have a query named MyQuery in my-query.graphql file, this template will generate the following code:

declare module '*/my-query.graphql' {
  import { DocumentNode } from 'graphql'
  const MyQuery: DocumentNode
 
  export { MyQuery }
 
  export default defaultDocument
}

Accordingly, you can import the generated types and use it in your code:

import myQuery from './my-query.graphql'
 
// OR
 
import { myQuery } from './my-query.graphql'