graphql-codegen-typed-document-nodes
is a custom plugin for GraphQL Code Generator that generates typed document nodes for TypeScript operations and fragments. It enhances type safety by providing exportable types for GraphQL queries, mutations, and fragments.
- TypedDocumentNode generation: Automatically generates typed document nodes for operations and fragments.
- Type-safe GraphQL operations: Ensures queries, mutations, and fragments have precise TypeScript types.
- Seamless integration: Works as a plugin for GraphQL Code Generator.
- Pure ESM package
This plugin requires the @graphql-codegen/typescript-operations
plugin to function correctly.
Install via npm:
npm install -D graphql-codegen-typed-document-nodes @graphql-codegen/typescript-operations
Install via yarn:
yarn add -D graphql-codegen-typed-document-nodes @graphql-codegen/typescript-operations
This configuration will generate *.generated.{ts,tsx}
files for each .ts
or .tsx
file containing operations or fragments.
Here’s an example configuration using graphql-codegen-typed-document-nodes
in a codegen.ts
file:
import type { CodegenConfig } from "@graphql-codegen/cli";
const config: CodegenConfig = {
pluginLoader: (name) => import(name),
schema: "schema.graphql",
documents: "src/**/*.graphql",
ignoreNoDocuments: true,
generates: {
"./src/generated/common-types.ts": {
plugins: ["typescript"],
config: {
avoidOptionals: true,
},
},
".": {
preset: "near-operation-file",
plugins: ["typescript-operations", "typed-document-nodes"],
presetConfig: {
baseTypesPath: "./src/generated/common-types.ts",
},
config: {
inlineFragmentTypes: "mask",
},
},
},
};
export default config;
Given the following query:
const getUserQuery = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
`;
This plugin will generate the following type:
...
export type GetUserDocument = Types.TypedDocumentNode<GetUserQuery, GetUserQueryVariables>;
You can now use the generated type in your application:
import { GetUserDocument } from "./getUserQuery.generated.ts";
const getUserQuery: GetUserDocument = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
`;
Unable to load template plugin matching 'typed-document-nodes'.
Reason:
require() of ES Module graphql-codegen-typed-document-nodes/out/index.js fr…
Instead change the require of index.js in .yarn/__virtual__/@graphql-codegen-cli-vir…
Solution:
This error occurs because @graphql-codegen
expects the plugin to be loaded in a specific way. To resolve this, add a pluginLoader
function to your GraphQL Code Generator configuration:
import type { CodegenConfig } from "@graphql-codegen/cli";
const config: CodegenConfig = {
...
pluginLoader: (name) => import(name),
...
};
export default config;
This ensures the plugin is loaded as an ES module, preventing the require()
error.
All notable changes to this project will be documented in the CHANGELOG file.
This project is licensed under the MIT License. See the LICENSE file for details.