{"id":15391045,"url":"https://github.com/quramy/ts-graphql-plugin","last_synced_at":"2026-02-17T12:18:10.030Z","repository":{"id":19592428,"uuid":"87432483","full_name":"Quramy/ts-graphql-plugin","owner":"Quramy","description":"TypeScript Language Service Plugin for GraphQL developers","archived":false,"fork":false,"pushed_at":"2025-05-12T17:22:50.000Z","size":11718,"stargazers_count":743,"open_issues_count":31,"forks_count":26,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-05-12T18:32:59.923Z","etag":null,"topics":["graphql","language-server","plugin","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Quramy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2017-04-06T13:28:11.000Z","updated_at":"2025-05-12T09:27:32.000Z","dependencies_parsed_at":"2023-02-18T21:31:17.187Z","dependency_job_id":"54bc3330-a1a4-4a5c-b31d-9872e4339ce3","html_url":"https://github.com/Quramy/ts-graphql-plugin","commit_stats":{"total_commits":1742,"total_committers":16,"mean_commits":108.875,"dds":0.6079219288174512,"last_synced_commit":"724e6d14001cd2ad57402d9d8f47a3c2cdf59726"},"previous_names":[],"tags_count":60,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Quramy%2Fts-graphql-plugin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Quramy%2Fts-graphql-plugin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Quramy%2Fts-graphql-plugin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Quramy%2Fts-graphql-plugin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Quramy","download_url":"https://codeload.github.com/Quramy/ts-graphql-plugin/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254076850,"owners_count":22010611,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","language-server","plugin","typescript"],"created_at":"2024-10-01T15:09:45.008Z","updated_at":"2026-02-17T12:18:10.024Z","avatar_url":"https://github.com/Quramy.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ts-graphql-plugin\n\n[![github actions](https://github.com/Quramy/ts-graphql-plugin/workflows/build/badge.svg)](https://github.com/Quramy/ts-graphql-plugin/actions)\n[![codecov](https://codecov.io/gh/Quramy/ts-graphql-plugin/branch/main/graph/badge.svg)](https://codecov.io/gh/Quramy/ts-graphql-plugin)\n[![npm version](https://badge.fury.io/js/ts-graphql-plugin.svg)](https://badge.fury.io/js/ts-graphql-plugin)\n[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/Quramy/ts-graphql-plugin/main/LICENSE.txt)\n\nProvides functions to help TypeScript GraphQL client development including auto completion, query validation, type generation and so on.\n\n![VSCode screenshot](https://raw.githubusercontent.com/Quramy/ts-graphql-plugin/main/capture_v4.gif)\n\nThis plugin has the following features:\n\n- As TypeScript Language Service extension:\n  - Completion suggestion\n  - Get GraphQL diagnostics\n  - Go to fragment definition\n  - Display GraphQL quick info within tooltip\n- As CLI\n  - Generate ts type files from your GraphQL operations in your TypeScript sources\n  - Extract or validate GraphQL operations in your TypeScript sources\n- As webpack plugin\n  - Transform your queries to GraphQL AST object statically\n\n## ToC\n\n\u003c!-- toc --\u003e\n\n- [Getting started](#getting-started)\n- [CLI Usage](#cli-usage)\n  - [`typegen` command](#typegen-command)\n  - [`extract` command](#extract-command)\n  - [`validate` command](#validate-command)\n  - [`report` command](#report-command)\n- [Plugin options](#plugin-options)\n  - [`schema`](#schema)\n  - [`tag`](#tag)\n  - [`exclude`](#exclude)\n  - [`enabledGlobalFragments`](#enabledglobalfragments)\n  - [`localSchemaExtensions`](#localschemaextensions)\n  - [`typegen.addons`](#typegenaddons)\n- [Built-in Type Generator Addons](#built-in-type-generator-addons)\n  - [`typed-query-document`](#typed-query-document)\n- [webpack custom transformer](#webpack-custom-transformer)\n  - [webpack plugin options](#webpack-plugin-options)\n    - [`tsconfigPath` optional](#tsconfigpath-optional)\n  - [Transformer options](#transformer-options)\n    - [`removeFragmentDefinitions` optional](#removefragmentdefinitions-optional)\n    - [`documentTransformers` optional](#documenttransformers-optional)\n- [Available editors](#available-editors)\n  - [VSCode](#vscode)\n- [Contributing](#contributing)\n- [License](#license)\n\n\u003c!-- tocstop --\u003e\n\n## Getting started\n\nFirst, confirm that your project has TypeScript and graphql(v15.x.0 or later).\n\nTo install this plugin, execute the following:\n\n```sh\nnpm install ts-graphql-plugin -D\n```\n\nAnd configure `plugins` section in your tsconfig.json, for example:\n\n```json\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"ts-graphql-plugin\",\n        \"schema\": \"path-or-url-to-your-schema.graphql\"\n      }\n    ]\n  }\n}\n```\n\nIt's ready to go. Launch your TypeScript IDE.\n\n## CLI Usage\n\n```sh\n$ npx ts-graphql-plugin \u003ccommand\u003e [options]\n```\n\nIf you install this plugin, a short alias `tsgql` is also available instead of `ts-graphql-plugin`.\n\nAvailable commands are `typegen`, `extract`, `validate` and `report`. If you want more detail, run `ts-graphql-plugin --help` or `ts-graphql-plugin \u003ccommand\u003e --help` in your console.\n\n### `typegen` command\n\nGenerate TypeScript types from GraphQL operations or fragments in your .ts source files. [Here is an output example](https://github.com/Quramy/ts-graphql-plugin/blob/main/project-fixtures/react-apollo-prj/src/__generated__/git-hub-query.ts).\n\n### `extract` command\n\nExtracts GraphQL operations and fragments from ts files and writes them to `manifest.json`.\n\n### `validate` command\n\nValidates your GraphQL operations and fragments in your ts files and report syntax or semantic errors.\n\n### `report` command\n\nExtracts GraphQL operations and fragments from ts files and report them to a Markdown file. [Here is an output example](https://github.com/Quramy/ts-graphql-plugin/blob/main/project-fixtures/react-apollo-prj/GRAPHQL_OPERATIONS.md).\n\n## Plugin options\n\nPass plugin options to your tsconfig.json to configure this plugin.\n\n```js\n/* tsconfig.json */\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"ts-graphql-plugin\",\n        /* plugin options */\n        \"schema\": \"path-or-url-to-your-schema.graphql\",\n        \"exclude\": [\"__generated__\"],\n        ...\n      }\n    ]\n  }\n}\n```\n\n### `schema`\n\nIt's a required parameter and should point your GraphQL schema SDL file such as :\n\n```graphql\ntype Author {\n  id: ID!\n  firstName: String\n  lastName: String\n  posts: [Post]\n}\ntype Post {\n  id: ID!\n  title: String\n  author: Author\n  votes: Int\n}\ntype Query {\n  posts: [Post]\n  author(id: ID!): Author\n}\n```\n\nAlso you can use GraphQL introspection query result data such as:\n\n```js\n{\n  \"__schema\": {\n    \"queryType\": {\n      \"name\": \"Query\"\n    },\n    \"types\": [\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"Query\",\n        \"description\": null,\n        \"fields\": [\n          {\n            \"name\": \"viewer\",\n            :\n```\n\nYou can pass URL and custom HTTP headers. It's useful to use an existing GraphQL server like [GitHub v4 API](https://developer.github.com/v4/). For example:\n\n```json\n  \"schema\": {\n    \"http\": {\n      \"url\": \"https://api.github.com/graphql\",\n      \"headers\": {\n        \"Authorization\": \"Bearer YOUR_GITHUB_API_TOKEN\"\n      }\n    }\n  },\n```\n\nIf you need to use more complex logic like fetch bearer token using client secret then you can build your http schema configuration using javascript. First, you need to setup your plugin configuration like below:\n\n```json\n  \"schema\": {\n    \"http\": {\n      \"fromScript\": \"my-graphql-config.js\"\n    }\n  },\n```\n\nYour script have to return valid `RequestSetup` or `Promise\u003cRequestSetup\u003e` object:\n\n```ts\nurl: string;\nmethod?: string; // default to 'POST'\nheaders?: { [key: string]: string };\n```\n\nExample how configuration script may look like:\n\n```js\n// my-graphql-config.js\nmodule.exports = projectRootPath =\u003e\n  new Promise(resolve =\u003e {\n    fetch('http://localhost/identity-server/connect/token', {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/x-www-form-urlencoded',\n      },\n      body: `client_secret=${process.env.MY_CLIENT_SECRET}`,\n    })\n      .then(response =\u003e response.json())\n      .then(response =\u003e {\n        resolve({\n          url: 'http://localhost/graphql',\n          method: 'POST', // unnecessary, \"POST\" is default value\n          headers: {\n            Authorization: `Bearer ${response.access_token}`,\n          },\n        });\n      });\n  });\n```\n\nThe `schema` option accepts the following type:\n\n```ts\ntype SchemaConfig =\n  | string\n  | {\n      file: {\n        path: string;\n      };\n    }\n  | {\n      http: {\n        url: string;\n        method?: string;\n        headers?: { [key: string]: string };\n      };\n    }\n  | {\n      http: {\n        fromScript: string;\n      };\n    };\n```\n\n### `tag`\n\nIt's optional and the default value is `[\"gql\", \"graphql\"]`. This value is used to find template literal strings of GraphQL document in your sources.\n\nFor example:\n\n```js\n/* tsconfig.json */\n\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"ts-graphql-plugin\",\n        \"tag\": \"myGraphqlTag\"\n      }\n    ]\n  }\n}\n```\n\n```ts\n// Recognized as GraphQL document\nconst query1 = myGraphqlTag`\n  query AppQuery {\n    __typename\n  }\n`;\n// Function call expression is also available.\nconst query2 = myGraphqlTag(`\n  query AppQuery {\n    __typename\n  }\n`);\n\n// The followings are not recognized as GraphQL document:\nconst str3 = `\u003cdiv\u003e\u003c/div\u003e`;\nconst str4 = otherTagFn`foooo`;\nconst otherValue = otherFn(`foooo`);\n```\n\nThe `tag` option accepts the following type:\n\n```ts\ntype TagConfig =\n  | undefined\n  | string\n  | string[]\n  | {\n      name?: string | string[];\n      ignoreFunctionCallExpression?: boolean;\n    };\n```\n\n\u003e [!NOTE]\n\u003e The `ignoreFunctionCallExpression` key exists only for backward compatibility with old versions. You don't need to explicitly use this.\n\n### `exclude`\n\nIt's optional. Specify an array of file or directory names when you want to exclude specific TypeScript sources from the plugin's analysis.\n\nIt's useful when other code generator copies your GraphQL document template strings.\n\n```js\n/* tsconfig.json */\n\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"ts-graphql-plugin\",\n        \"exclude\": [\n          \"src/gql\", // Ignore source files under `gql` directory\n          \"**/*.test.tsx\" // Ignore test files\n        ]\n      }\n    ]\n  }\n}\n```\n\n\u003e [!TIP]\n\u003e Wildcard characters, `*`, `**`, and `?` are available.\n\n\u003e [!NOTE]\n\u003e The plugin processes only TypeScript sources in your project by default. You don't need list default excluded files(e.g. `node_modules`).\n\n### `enabledGlobalFragments`\n\nIt's optional and the default value is `true`. If enabled, the plugin automatically searches for and merges the dependent fragments for the target GraphQL operation in the TypeScript project.\n\n```tsx\n/* Post.tsx */\n\nimport { graphql } from './gql';\n\nconst postFragment = graphql(`\n  fragment PostFragment on Post {\n    id\n    name\n    title\n  }\n`);\n\n/* App.tsx */\n\nconst appQuery = graphql(`\n  query AppQuery {\n    posts {\n      id\n      ...PostFragment\n    }\n  }\n`);\n```\n\nIn the above example, note that `${postFragment}` is not in the `appQuery` template string literal.\n\nIf this option is set `true`, you can go to definition of the fragment from the location where the fragment is used as spread reference.\n\n\u003e [!IMPORTANT]\n\u003e This option does not depend on whether the query and fragment are combined at runtime.\n\u003e Whether or not query and fragment are eventually combined depends on the build toolchain you are using.\n\u003e For example, [graphql-codegen](https://the-guild.dev/graphql/codegen/docs/guides/react-vue#writing-graphql-fragments) and [Gatsby](https://www.gatsbyjs.com/docs/reference/graphql-data-layer/using-graphql-fragments/) have a mechanism for referencing global fragments.\n\n\u003e [!IMPORTANT]\n\u003e Fragments must be given a unique name if this option is enabled.\n\n### `localSchemaExtensions`\n\nIt's optional. If you want to extend server-side schema, derived from `schema` option, you can set path of SDL file of your local extension.\n\nFor example:\n\n```graphql\n# local-extension.graphql\n\ndirective @client on FIELD\n\ntype SomeClientOnlyType {\n  name: String!\n}\n\nextend type Query {\n  someLocalField: SomeClientOnlyType!\n}\n```\n\n```js\n/* tsconfig.json */\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"ts-graphql-plugin\",\n        \"schema\": \"base-schema.graphql\",\n        \"localSchemaExtensions\": [\"local-extension.graphql\"]\n      }\n    ]\n  }\n}\n```\n\nThe above example setting allows to write the following query:\n\n```ts\nconst query = gql`\n  query {\n    someLocalField @client {\n      name\n    }\n  }\n`;\n```\n\n### `typegen.addons`\n\nIt's optional. You can extend CLI's [`typegen` command](#typegen-command) with this option.\n\nFor example, the following configuration loads `my-addon.ts`, which is an Addon to map `URL` custom GraphQL scalar field to TypeScript string type.\n\n```js\n/* tsconfig.json */\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"ts-graphql-plugin\",\n        \"schema\": \"schema.graphql\",\n        \"typegen\": {\n          \"addons\": [\n            \"./my-addon\"\n          ]\n        }\n      }\n    ]\n  }\n}\n```\n\n```ts\n/* my-addon.ts */\n\nimport ts from 'typescript';\nimport { TypeGenAddonFactory } from 'ts-graphql-plugin';\n\nconst addonFactory: TypeGenAddonFactory = () =\u003e ({\n  customScalar({ scalarType }) {\n    if (scalarType.name === 'URL') {\n      return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);\n    }\n  },\n});\n\nmodule.exports = addonFactory;\n```\n\nThe `addons` property accepts an array of strings. And each string should point Node.js module which implements `TypeGenAddonFactory` interface. You can pass not only \".js\" files but also \".ts\" files.\n\nIf you learn how to create your Addon, see [type generator customization guide](docs/CUSTOMIZE_TYPE_GEN.md) for more details.\n\nts-graphql-plugin also provides built-in Addons. See also the [Built-in Type Generator Addons](#built-in-type-generator-addons) section.\n\n## Built-in Type Generator Addons\n\n### `typed-query-document`\n\nThis Addon requires `graphql` v15.4.0 or later. To enable this feature, configure as the following:\n\n```js\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"ts-graphql-plugin\",\n        \"tag\": \"gql\",\n        \"schema\": \"schema.graphql\",\n        \"typegen\": {\n          \"addons\": [\n            \"ts-graphql-plugin/addons/typed-query-document\"\n          ]\n        }\n      }\n    ]\n  }\n}\n```\n\nWhen enabled generated files export a type based on [`TypedQueryDocumentNode`](https://the-guild.dev/blog/typed-document-node) from GraphQL. The type extends the standard `DocumentNode` AST type but also includes types for result data and variables as type arguments.\n\nTo use this feature you can apply a type assertion to `gql` template tag expressions that evaluate to a `DocumentNode` value.\n\nFor example:\n\n```ts\nconst query = gql`\n  query MyQuery($take: Int!) {\n    recipes(take: $take) {\n      id\n      title\n    }\n  }\n` as import('./__generated__/my-query.ts').MyQueryDocument;\n```\n\nWith that type assertion in place result data and variable types will automatically flow through any function that accepts the `TypedQueryDocumentNode` type.\n\nFor example here is how you can write a wrapper for the `useQuery` function from Apollo Client:\n\n```ts\nimport { gql, QueryHookOptions, QueryResult, useQuery } from '@apollo/client';\nimport { TypedQueryDocumentNode } from 'graphql';\nfunction useTypedQuery\u003cResponseData, Variables\u003e(\n  query: TypedQueryDocumentNode\u003cResponseData, Variables\u003e,\n  options: QueryHookOptions\u003cResponseData, Variables\u003e,\n): QueryResult\u003cResponseData, Variables\u003e {\n  return useQuery(query, options);\n}\n// example usage\nconst { data } = useTypedQuery(query, { variables: { take: 100 } });\n//      ^                                          ^\n//      inferred type is `MyQuery`                 |\n//                                                 |\n//                                        inferred type is `MyQueryVariables`\n```\n\nThe result is that generated types are associated with queries at the point where the query is defined instead of at the points where the query is executed.\n\n## webpack custom transformer\n\nts-graphql-plugin provides TypeScript custom transformer to static transform from query template strings to GraphQL AST. It's useful if you use https://github.com/apollographql/graphql-tag\n\n```js\n/* webpack.config.js */\nconst TsGraphQLPlugin = require('ts-graphql-plugin/webpack');\n\nconst tsgqlPlugin = new TsGraphQLPlugin({\n  /* plugin options */\n});\n\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.tsx?$/,\n        exclude: /node_modules/,\n        loader: 'ts-loader',\n        options: {\n          getCustomTransformers: () =\u003e ({\n            before: [\n              tsgqlPlugin.getTransformer({\n                /* transformer options */\n              }),\n            ],\n          }),\n        },\n      },\n    ],\n  },\n  plugins: [tsgqlPlugin],\n};\n```\n\n\u003e [!NOTE]\n\u003e For now, this plugin transforms nothing when webpack's `--mode` option is `development` and webpack runs with `--watch` option.\n\n### webpack plugin options\n\n#### `tsconfigPath` optional\n\nSet your project tsconfig json's file path. Default value: `tsconfig.json`.\n\n### Transformer options\n\n#### `removeFragmentDefinitions` optional\n\nDefault: `true`. If set, the transformer transforms template strings which include only GraphQL fragment definitions to empty string literal.\n\nFor example, we finally does not need the GraphQL AST document of `fragment`. We need interpolated GraphQL query AST for `query`. So this transformer statically resolves `${fragment}` interpolation and removes right-hand-side of the `fragment` variable.\n\n```ts\nconst fragment = gql`\n  fragment MyFragment on Query {\n    hello\n  }\n`;\n\nconst query = gql`\n  ${fragment}\n  query MyQuery {\n    ...MyFragment\n  }\n`;\n```\n\n#### `documentTransformers` optional\n\nDefault: `[]`. You can set an array of GraphQL AST document visitor functions. The visitor functions should be compatible to https://graphql.org/graphql-js/language/#visit .\n\n## Available editors\n\nI've checked the operation with the following editors:\n\n- VSCode\n- Vim (with tsuquyomi)\n\nAnd the following editor have TypeScript plugin with LanguageService so they're compatible with this plugin:\n\n- Emacs\n- Sublime text\n- Eclipse\n\n### VSCode\n\nTo use TypeScript Language Service Plugin within VSCode, confirm your VSCode uses [workspace version TypeScript](https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-the-workspace-version-of-typescript).\n\n```js\n/* .vscode/settings.json */\n\n{\n  \"typescript.tsdk\": \"node_modules/typescript/lib\",\n  \"typescript.enablePromptUseWorkspaceTsdk\": true\n}\n```\n\n## Contributing\n\nSee [contribution guide](CONTRIBUTING.md).\n\n## License\n\nThis software is released under the MIT License, see LICENSE.txt.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fquramy%2Fts-graphql-plugin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fquramy%2Fts-graphql-plugin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fquramy%2Fts-graphql-plugin/lists"}