微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当 Apollo Server 处于生产模式时,如何借助 graphql-codegen 为 React 生成 Graphql 类型?

如何解决当 Apollo Server 处于生产模式时,如何借助 graphql-codegen 为 React 生成 Graphql 类型?

当后端模式设置为 NODE_ENV: development 时一切正常,但在生产模式下 graphql-codegen 失败并出现错误

本地网络服务器错误

Apollo Server 不允许 GraphQL 自省,但查询 包含 _schema 或 _type。要启用内省,请通过 内省:生产中的 ApolloServer 是真实的

生产网络服务器错误

无法从 https://example.com/graphql 加载架构,原因:无法 验证第一个证书。 GraphQL 代码生成支持

  • ES 模块和 Commonjs 导出(认导出或命名导出“模式”)
  • 内省 JSON 文件
  • GraphQL 端点的 URL
  • 具有类型定义(全局表达式)的多个文件
  • 配置文件中的字符串

前端 codegen.yml:

schema: ${REACT_APP_GRAPHQL_URL}
documents:
 - './src/GraphQL/queries/query.ts'    
 - './src/GraphQL/mutations/mutation.ts'
overwrite: true
generates:
  ./src/generated/graphql.tsx:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      skipTypename: false
      withHooks: true
      withHOC: false
      withComponent: false

前端开发依赖:

{
    "@graphql-codegen/cli": "^1.20.1","@graphql-codegen/typescript": "^1.20.2","@graphql-codegen/typescript-operations": "^1.17.14","@graphql-codegen/typescript-react-apollo": "^2.2.1",}

npm 脚本:

{
    "generate": "graphql-codegen -r dotenv/config --watch --config codegen.yml","prebuild": "graphql-codegen -r dotenv/config --config codegen.yml"
}

./src/generated/ 目录添加到 .gitignore

解决方法

我的解决方案是将内省插件和单独的 codegen.yml 文件添加到:

  • codegen-generate-schema-json
  • codegen-generate-typescript
devDependencies: {"@graphql-codegen/introspection": "^1.18.1"}

codegen-generate-typescript.yml:

schema: graphql.schema.json
documents:
  - './src/GraphQL/queries/query.ts'
  - './src/GraphQL/mutations/mutation.ts'
overwrite: true
generates:
  ./src/generated/graphql.tsx:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      skipTypename: false
      withHooks: true
      withHOC: false
      withComponent: false

codegen-generate-schema-json.yml:

schema: ${REACT_APP_GRAPHQL_URL}
overwrite: true
generates:
  ./graphql.schema.json:
    plugins:
      - introspection

所以 ./graphql.schema.json 文件需要提交并用作模式源而不是 URI。

也许您建议更好的解决方案?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。