You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apollo Angular GraphQL代码生成:仅生成类型,缺失查询/变更类?

问题:Apollo Angular代码生成仅生成类型,未生成PostsGQL等操作类

我尝试用Apollo Angular代码生成工具从单个schema.graphqls文件生成类型、查询和变更,使用的schema如下:

type Author {
  id: Int!
  firstName: String!
  lastName: String!
  posts(findTitle: String): [Post]
}
 
type Post {
  id: Int!
  title: String!
  author: Author
}
 
type Query {
  posts: [Post]
}

已安装必要依赖:

npm install graphql
npm install -D typescript
npm install -D @graphql-codegen/cli
npm install -D @graphql-codegen/typescript
npm install -D @graphql-codegen/typescript-operations
npm install -D @graphql-codegen/typescript-apollo-angular

使用的codegen.ts配置:

import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: './schema.graphqls',
  generates: {
    './src/app/graphql/generated.ts': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typescript-apollo-angular',
      ],
    },
  },
};
export default config;

执行npm run generate后成功生成文件,但仅包含类型定义,缺失指南示例中的PostsGQL这类GQL操作类,schema中的查询也未出现在生成文件里。疑问:是否需要单独指定查询和变更?原因是什么?


解决方案

核心原因

GraphQL Codegen生成XXXGQL这类Angular操作类,需要具体的查询/变更语句文档,而非仅依赖schema中定义的Query/Mutation类型结构。schema仅描述API的可用操作和数据类型,但Codegen需要知道你实际要调用哪些具体查询,才能生成对应的服务类。

解决步骤

  1. 创建查询文档文件
    在项目中创建包含具体查询语句的.graphql文件,比如src/app/graphql/queries.graphql,写入你需要的查询:
# 定义具体的查询语句
query GetPosts {
  posts {
    id
    title
    author {
      id
      firstName
      lastName
    }
  }
}
  1. 修改codegen.ts配置
    添加documents字段,指向你的查询/变更文件(支持通配符匹配多个文件):
import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: './schema.graphqls',
  documents: './src/app/graphql/**/*.graphql', // 匹配所有.graphql格式的查询/变更文件
  generates: {
    './src/app/graphql/generated.ts': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typescript-apollo-angular',
      ],
    },
  },
};
export default config;
  1. 重新执行生成命令
    运行npm run generate,此时生成的generated.ts文件会包含GetPostsGQL类,以及对应的查询类型定义。

内容的提问来源于stack exchange,提问作者IdealOutage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:25:18