LoginSignup
1
0

More than 5 years have passed since last update.

graphql-codegenでComponentが生成されなくてハマった件

Last updated at Posted at 2019-05-07

目的

graphql-codegenのGenerate機能を使って定義したQueryのReact.Componentを生成したい

状況

以下、codegen.ymlを一部抜粋

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

documents: './main/graphql/**/*.ts'
main/graphql配下のtsファイルがインクルードされる想定

main/graphql/queries/item.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.tsxReact.Componentが出力される想定だったが出力されない…

解決策

main/graphql/queries/item.ts
import gql from 'graphql-tag';

Qureyを定義する際 graphql-tag から gql をインポートしていたのが原因だった。

正しくは apollo-boost からインポートする

main/graphql/queries/item.ts
- import gql from 'graphql-tag';
+ import { gql } from 'apollo-boost';

上記に修正して再度実行

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

  ✔ Parse configuration
  ✔ Generate outputs
apolloComponents.tsx
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が出力されました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0