简体   繁体   English

如何为 graphql 生成 TypeScript 定义

[英]How to generate TypeScript definitions for graphql

I have a react app based on create react app and TypeScript.我有一个基于 create react app 和 TypeScript 的 react 应用程序。 I want to replace redux with Apollo graphql client.我想用 Apollo graphql 客户端替换 redux。 I define queries in .graphql files and/or gql-Tag using string templates.我使用字符串模板在 .graphql 文件和/或 gql-Tag 中定义查询。 I want the result/data from apollo's Query component to be strongly typed, how can I do that?我希望来自 apollo 的 Query 组件的结果/数据是强类型的,我该怎么做? Without writing interfaced and types myself, I want them to be generated 😬无需自己编写接口和类型,我希望生成它们😬

There is a very good tool for that called Apollo codegen , it's part of apollo-cli.有一个非常好的工具叫做Apollo codegen ,它是 apollo-cli 的一部分。

Have a look into their documentation: https://github.com/apollographql/apollo-cli#apollo-codegengenerate-output看看他们的文档: https : //github.com/apollographql/apollo-cli#apollo-codegengenerate-output

An example to generate the TypeScript definitions would be:生成 TypeScript 定义的示例是:

  • Download the schema of your server:下载服务器的架构:

apollo schema:download .schema/graphql.json --endpoint=http://localhost:4000/

  • Generate the types for your queries:为您的查询生成类型:

apollo codegen:generate --schema=.schema/graphql.json --addTypename --target=typescript --queries=src/**/*.{tsx,ts} --outputFlat=src/queries

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM