加载 .graphql 文件
要加载 .gql
和 .graphql
文件,首先通过运行安装 graphql
和 graphql.macro
包:
¥To load .gql
and .graphql
files, first install the graphql
and graphql.macro
packages by running:
npm install --save graphql graphql.macro
或者你可以使用 yarn
:
¥Alternatively you may use yarn
:
yarn add graphql graphql.macro
然后,每当你想加载 .gql
或 .graphql
文件时,从宏包中导入 loader
:
¥Then, whenever you want to load .gql
or .graphql
files, import the loader
from the macro package:
import { loader } from 'graphql.macro';
const query = loader('./foo.graphql');
你的结果会自动内联!这意味着如果上面的文件 foo.graphql
包含以下内容:
¥And your results get automatically inlined! This means that if the file above, foo.graphql
, contains the following:
query {
hello {
world
}
}
前面的例子变成:
¥The previous example turns into:
const query = {
'kind': 'Document',
'definitions': [{
...
}],
'loc': {
...
'source': {
'body': '\\\\n query {\\\\n hello {\\\\n world\\\\n }\\\\n }\\\\n',
'name': 'GraphQL request',
...
}
}
};
你还可以像使用 graphql-tag
包中的非宏版本一样使用 gql
模板标记,并具有内联解析结果的额外好处。
¥You can also use the gql
template tag the same way you would use the non-macro version from graphql-tag
package with the added benefit of inlined parsing results.
import { gql } from 'graphql.macro';
const query = gql`
query User {
user(id: 5) {
lastName
...UserEntry1
}
}
`;