我对于无法通过graphql-codegen生成组件而陷入困境

目标

我想使用 graphql-codegen 的 Generate 功能来生成定义的查询的 React.Component。

情况

以下是对codegen.yml文件的部分摘录

documents: './main/graphql/**/*.ts'
generates:
  ./main/generated/apolloComponents.tsx:
    config:
      noNamespaces: true
      scalars:
        BigDecimal: string
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
  ./main/generated/resolverTypes.tsx:
    config:
      useIndexSignature: true
    plugins:
      - typescript
      - typescript-resolvers

文档: ‘./main/graphql/**/*.ts’
预计包含在main/graphql目录下的ts文件。

import gql from 'graphql-tag';

export const itemQuery = gql`
  query Item($id: String!) {
    item(id: $id) {
      id
      name
    }
  }
`;

定义一个查询(Query),然后执行以下命令

$ gql-gen --config ./codegen.yml

  ✔ Parse configuration
  ✔ Generate outputs

这本来应该在 apolloComponents.tsx 中输出 React.Component,但却没有输出…

解決方法

import gql from 'graphql-tag';

导致问题的原因是在定义Query时从graphql-tag导入了gql。

应该从 apollo-boost 中导入

- import gql from 'graphql-tag';
+ import { gql } from 'apollo-boost';

请按照上述修正进行再次执行。

$ gql-gen --config ./codegen.yml

  ✔ Parse configuration
  ✔ Generate outputs
import gql from 'graphql-tag';
import * as React from 'react';
import * as ReactApollo from 'react-apollo';

export const ItemDocument = gql`
    query Item($id: String!) {
  item(id: $id) {
    id
    name
  }
}
    `;

export class ItemComponent extends React.Component<Partial<ReactApollo.QueryProps<ItemQuery, ItemQueryVariables>>> {
  render() {
      return (
          <ReactApollo.Query<ItemQuery, ItemQueryVariables> query={ItemDocument} {...(this as any)['props'] as any} />
      );
  }
}
export type ItemProps<TChildProps = {}> = Partial<ReactApollo.DataProps<ItemQuery, ItemQueryVariables>> & TChildProps;
export function withItem<TProps, TChildProps = {}>(operationOptions: ReactApollo.OperationOption<
  TProps,
  ItemQuery,
  ItemQueryVariables,
  ItemProps<TChildProps>> | undefined) {
    return ReactApollo.withQuery<TProps, ItemQuery, ItemQueryVariables, ItemProps<TChildProps>>(ItemDocument, operationOptions);
};

一切顺利,成功输出了React.Component!

广告
将在 10 秒后关闭
bannerAds