【问题标题】:How to generate Graphql types for React with help of graphql-codegen when Apollo Server is in production mode?当 Apollo Server 处于生产模式时,如何在 graphql-codegen 的帮助下为 React 生成 Graphql 类型?
【发布时间】:2021-07-08 15:37:23
【问题描述】:

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

本地网络服务器错误:

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

生产网络服务器错误:

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

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

前端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

【问题讨论】:

  • 向 API/服务器维护人员询问有关提供可下载/静态预生成 [on build/deploy] 架构文件的问题

标签: node.js typescript graphql apollo graphql-codegen


【解决方案1】:

我的解决方案是添加自省插件并将 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。

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

【讨论】:

  • 或者你可以直接提交 generated.tsx
猜你喜欢
  • 2020-12-21
  • 2021-08-29
  • 2019-11-12
  • 2020-03-22
  • 1970-01-01
  • 2019-09-08
  • 2020-02-29
  • 2018-08-17
  • 2020-12-05
相关资源
最近更新 更多