中继编译器
graphql
中继提供的 graphql
模板标签是用于在 GraphQL 语言中编写查询、片段、变异和订阅的机制。例如
import {graphql} from 'react-relay';
graphql`
query MyQuery {
viewer {
id
}
}
`;
使用 graphql
模板标签的结果是 GraphQLTaggedNode
;GraphQL 文档的运行时表示。
请注意,graphql
模板标签**永远不会在运行时执行**。相反,它们由中继编译器提前编译成生成的工件,这些工件与您的源代码一起存在,并且中继在运行时需要这些工件才能运行。
编译器
中继使用中继编译器将graphql
文本转换为与您的源文件并存的生成文件。
像以下这样的片段
graphql`
fragment MyComponent on Type {
field
}
`
将导致一个生成文件出现在 ./__generated__/MyComponent.graphql.js
中,其中包含运行时工件(有助于从中继存储读取和写入)和 Flow 类型,以帮助您编写类型安全的代码。
中继编译器负责在构建步骤中生成代码,这些代码可以在运行时引用。通过提前构建查询,中继的运行时不需要负责生成查询字符串,并且可以在查询上执行各种优化,这些优化在运行时可能过于昂贵(例如,在构建步骤中可以合并查询中重复的字段,以提高处理 GraphQL 响应的效率)。
GraphQL 模式
要使用中继编译器,您需要一个 .graphql
GraphQL 模式 文件,描述您的 GraphQL 服务器的 API。通常,这些文件是服务器真实来源的本地表示,不会直接编辑。例如,我们可能有一个 schema.graphql
,如下所示
schema {
query: Root
}
type Root {
dictionary: [Word]
}
type Word {
id: String!
definition: WordDefinition
}
type WordDefinition {
text: String
image: String
}
运行编译器
此外,您需要一个包含使用 graphql
标签描述 GraphQL 查询和片段的 .js
文件的目录。让我们将其称为 ./src
。
然后运行 yarn run relay
,如之前设置一样。
这将创建一系列与包含 graphql
标签的相应文件同级存在的 __generated__
目录。
例如,给定这两个文件
src/Components/DictionaryComponent.js
const DictionaryWordFragment = graphql`
fragment DictionaryComponent_word on Word {
id
definition {
...DictionaryComponent_definition
}
}
`
const DictionaryDefinitionFragment = graphql`
fragment DictionaryComponent_definition on WordDefinition {
text
image
}
`
src/Queries/DictionaryQuery.js
const DictionaryQuery = graphql`
query DictionaryQuery {
dictionary {
...DictionaryComponent_word
}
}
`
这将生成三个生成文件和两个 __generated__
目录
src/Components/__generated__/DictionaryComponent_word.graphql.js
src/Components/__generated__/DictionaryComponent_definition.graphql.js
src/Queries/__generated__/DictionaryQuery.graphql.js
导入生成定义
通常您不需要导入生成的定义。然后,Relay Babel 插件 将把您代码中的 graphql
文本转换为对生成文件的 require()
调用。
但是,中继编译器还自动生成 Flow 类型,作为 类型注释。例如,您可以像这样导入生成的 Flow 类型
import type {DictionaryComponent_word} from './__generated__/DictionaryComponent_word.graphql';
更罕见的是,您可能需要从多个文件访问查询、变异、片段或订阅。在这些情况下,您也可以直接导入它
import DictionaryComponent_word from './__generated__/DictionaryComponent_word.graphql';
此页面是否有用?
通过以下操作帮助我们改进网站 回答几个简短的问题.