blog.mahoroi.com

GraphQL Code Generatorで@apollo/clientを使う

-

graphql-code-generator で React Client 用の定義ファイルを生成すると、@apollo/react-common をインポートしたファイルが出力されます。

package.json
{
  "dependencies": {
    "@apollo/client": "3.0.0-beta.20"
  },
  "devDependencies": {
    "@graphql-codegen/cli": "1.12.2",
    "@graphql-codegen/typescript": "1.12.2",
    "@graphql-codegen/typescript-operations": "1.12.2",
    "@graphql-codegen/typescript-react-apollo": "1.12.2",
    "typescript": "3.7.4"
  }
}
codegen.yml
overwrite: true
schema: src/graphql/schema.graphql
documents: src/graphql/**/*.graphql
generates:
  src/types/graphql/client.tsx:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      withComponent: false
      withHOC: false
      withHooks: true
src/types/graphql/client.tsx
import gql from 'graphql-tag';
import * as ApolloReactCommon from '@apollo/react-common'; // これ
import * as ApolloReactHooks from '@apollo/react-hooks'; // これ
...

@apollo/clientを使う

@apollo/react-common ではなく @apollo/client を使いたいときは、codegen.yml に次のような設定を追加します。

codegen.yml
overwrite: true
schema: src/graphql/schema.graphql
documents: src/graphql/**/*.graphql
generates:
  src/types/graphql/client.tsx:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      withComponent: false
      withHOC: false
      withHooks: true
      apolloReactCommonImportFrom: "@apollo/client"
      apolloReactComponentsImportFrom: "@apollo/client"
      apolloReactHocImportFrom: "@apollo/client"
      apolloReactHooksImportFrom: "@apollo/client"
src/types/graphql/client.tsx
import gql from 'graphql-tag';
import * as ApolloReactCommon from '@apollo/client'; // こうなる
import * as ApolloReactHooks from '@apollo/client'; // こうなる
...

おしまい。

参考