跳至主要內容
版本:v18.0.0

Relay 編譯器

graphql

Relay 提供的 graphql 樣板標籤作為在 GraphQL 語言中編寫查詢、片段、突變和訂閱的機制。例如

import {graphql} from 'react-relay';

graphql`
query MyQuery {
viewer {
id
}
}
`;

使用 graphql 樣板標籤的結果是 GraphQLTaggedNode;GraphQL 文件的一個執行階段表示。

請注意,graphql 樣板標籤**絕不在執行階段執行**。相反,它們會由 Relay 編譯器預先編譯為產生的成品,這些成品與您的原始程式碼並存,且 Relay 需要這些成品才能在執行階段運作。

編譯器

Relay 使用 Relay 編譯器將 graphql 字面值轉換為與您的原始程式碼檔案並存的產生檔案。

像以下的片段

graphql`
fragment MyComponent on Type {
field
}
`

將導致產生一個檔案出現在 ./__generated__/MyComponent.graphql.js 中,其中包含執行階段成品 (協助從 Relay 儲存區讀取和寫入) 以及 Flow 類型,以協助您編寫類型安全程式碼。

Relay 編譯器負責在建置步驟中產生程式碼,然後可以在執行階段引用這些程式碼。透過預先建置查詢,Relay 的執行階段不負責產生查詢字串,並且可以在查詢上執行各種最佳化,這些最佳化在執行階段可能太耗費資源 (例如,查詢中重複的欄位可以在建置步驟期間合併,以提高處理 GraphQL 回應的效率)。

GraphQL 結構描述

若要使用 Relay 編譯器,您需要一個 .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() 呼叫。

然而,Relay 編譯器也會自動產生 Flow 類型作為 類型註解。例如,您可以像這樣匯入產生的 Flow 類型

import type {DictionaryComponent_word} from './__generated__/DictionaryComponent_word.graphql';

更罕見的情況下,您可能需要從多個檔案存取查詢、突變、片段或訂閱。在這些情況下,您也可以直接匯入它

import DictionaryComponent_word from './__generated__/DictionaryComponent_word.graphql';

這個頁面有用嗎?

透過以下方式幫助我們讓網站更好 回答幾個快速問題.