首页 > 解决方案 > 如何使用 graphql schema.json 为 graphql 类型生成 typescript 接口而不进行操作?

问题描述

如何从 schema.json 生成 Typescript 文件。graphql-codegenerator 和 apollo-codegen 似乎都没有提供从 schema.json 生成 typescript 接口的方法,而无需在操作中特定使用类型。

我现在为此挣扎了一段时间。有没有办法做到这一点?

标签: typescriptgraphql

解决方案


我的 schema.json 有一个标准的自省输出。我一直在努力寻找一种合适的方法来生成我的打字稿界面。

我实际上找到了一种方法:

代码生成.yml

schema:
    - http://my-graphql-api.com/graphql
    - ./local/schema.graphql
documents:
    - ./src/**/*.graphql
overwrite: true
clientSchema: ./local/schema.graphql
generates:
    src/graphql-types.ts:
        plugins:
            - typescript
            - typescript-operations
        config:
            declarationKind:
                union: type
                type: interface
                input: interface
                scalar: interface
                arguments: interface
                interface: interface
            enumsAsTypes: true
            includeDirectives: true
            commentDescriptions: true
            flattenGeneratedTypes: true
            avoidOptionals:
                field: false
                object: false
                inputValue: false

然后运行:graphql-code-generator --config ./codegen.yml

https://graphql-code-generator.com/docs/plugins/typescript

有没有办法用 apollo-codegen cli 做到这一点?


推荐阅读