npm.io
5.0.0 • Published 1 month ago

gql-webpack-loader

Licence
MIT
Version
5.0.0
Deps
0
Size
52 kB
Vulns
0
Weekly
0
Stars
1

GraphQL Rspack loader

npm version Build Status

The GraphQL rspack loader transforms .gql files into JavaScript modules and generates corresponding TypeScript declaration files (.d.ts), based on your generated GraphQL schema types. Note: compatible only with rspack 2.1.x. Use version 4.x.x for webpack, or for rspack 1.7.x. See the test snapshots for example output.

And in your JavaScript:

import GqlQuery from 'query.gql'

Install

npm install --save-dev gql-webpack-loader

or

yarn add gql-webpack-loader

Rspack configuration

{
    test: /\.(graphql|gql)$/,
    exclude: /node_modules/,
    loader: "gql-webpack-loader",
    options: {
        gqlSchemaPath: path.resolve(__dirname, '../fixtures/schema.ts'),
        declaration: true,    
        mutationInterfaceName: 'MutationModel',
        queryInterfaceName: 'QueryModel',
        variableInterfaceRe: (operationNode, fieldName) =>
            // This used by default 
            new RegExp(`(${operation.operation})(${fieldName + operation.fieldOperationName})argsmodel`, 'gmi')
    }    
}

Config

1. declaration
Type: boolean

Whether generate corresponding declaration (d.ts) file for generated module.

2. gqlSchemaPath
Type: string
Required if declaration is true

Path to TypeScript GraphQL schema. You can generate TypeScript schema with the next libraries

3. mutationInterfaceName
Type: string
Required if declaration is true

Name of your mutation model.

4. queryInterfaceName
Type: string
Required if declaration is true

Name of your query model

5. variableInterfaceRe
Type: (node: OperationNode) => RegExp
Optional

A function that takes an operation node as input, along with an optional nested field name, and returns a regular expression to validate variable imports. If no variable model is found, { [key: string]: any } will be used.

5. exportNameBy
Type: (fileName: string) => string
Optional

A function that takes a fileName as input and returns a name for the export clause in both the GraphQL JS module and its declaration.

Declaration usage

// you should provide GraphQL execution function & the result type
type Result<T = any> = {
    data?: T;
    errors?: Error[];
}

const execute = <T = any, V = Record<string, any>>(module: GqlModule<T, V>, variables?: V): Promise<Result<V>> => {
  // your graphql query execution implementation
}

// and later in your code
import GqlQuery from 'query.gql'
execute(GqlQuery.operation).then((response) =>
    // response will have a type information about your GraphQl query
    response.data.operation    
)

Keywords