跳至主要內容

載入 `.graphql` 檔案

要載入 `.`和 `.graphql` 檔案,請先安裝 `graphql` 和 `graphql.macro` 套件

npm install --save graphql graphql.macro

您也可以使用 yarn

yarn add graphql graphql.macro

然後,當您要載入 `.`或 `.graphql` 檔案時,請從 macro 套件導入 loader

import { loader } from 'graphql.macro';

const query = loader('./foo.graphql');

您的結果會自動內嵌!表示如果上方的檔案 `foo.graphql` 包含以下內容

query {
hello {
world
}
}

前一個範例會轉為

const query = {
'kind': 'Document',
'definitions': [{
...
}],
'loc': {
...
'source': {
'body': '\\\\n query {\\\\n hello {\\\\n world\\\\n }\\\\n }\\\\n',
'name': 'GraphQL request',
...
}
}
};

您也可以使用 `gql` 範本標籤,就像您會使用 `graphql-tag` 套件的非 macro 版本,並能額外獲得內嵌剖析結果。

import { gql } from 'graphql.macro';

const query = gql`
query User {
user(id: 5) {
lastName
...UserEntry1
}
}
`;