首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将类型从.graphql导入到.js文件

将类型从.graphql导入到.js文件
EN

Stack Overflow用户
提问于 2018-10-22 18:02:45
回答 1查看 1.7K关注 0票数 0

我从.graphql文件中搜索了一些关于导入类型的内容。我发现graphql-进口可以使用# import something from 'something-else'导入。这在.graphql文件之间工作得很好。

但是,我要做的是将一些typesgenerated.graphql中导入到.js文件中。

例如:

我有来自Prisma的这个generated.graphql文件

代码语言:javascript
复制
"""generated.graphql file"""
type ItemWhereInput { ... }

type ItemConnection { ... }

...

我想将这两种类型的ItemWhereInputItemConnectiongenerated.graphql文件导入到items-types.js文件中

代码语言:javascript
复制
// items-types.js file

import gql from 'graphql-tag';
// I would like to make some kind of import ItemWhereInput and ItemConnection here
// Something like `import { ItemWhereInput, ItemConnection } from 'generated.graphql'`

... 

const ItemWhereUniqueInput = gql`
  input ItemWhereUniqueInput {
    id: String!
  }
`;

... 

// And export ItemWhereInput and ItemConnection here
export default [Item, ItemInput, ItemWhereUniqueInput, ItemUpdateInput]; 

这样,我就可以从makeExecutableSchema调用graphql-tools,并在其他地方使用这些类型。

代码语言:javascript
复制
// items-query.js file

import { forwardTo } from 'prisma-binding';

const schema = `
  items: [Item]!
  item (where: ItemWhereUniqueInput!): Item

  # And use it here
  itemsConnection (where: ItemWhereInput): ItemConnection!
`;

const resolvers = {
  items: forwardTo(‘db’),
  item: forwardTo(‘db’),
  itemsConnection: forwardTo(‘db’),
};

export default {
  schema,
  resolvers,
};

如果它是在其他地方,或者有什么东西可以帮助,请指出我。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2019-04-01 10:03:36

您应该能够做到以下几点:

在构建步骤中,首先,通过以下方法将generated.graphql文件转换为js文件

  1. export default `添加到文件的开头,
  2. 到文件末尾的`);,以及
  3. 将其重命名为generated.js

这样,您就可以像js文件一样导入开发代码中的文件:

代码语言:javascript
复制
// some other js file

/* 
 * notice the lack of .js, this should make it easier for your 
 * IDE to understand you're referencing the 'generated.graphql' file.
 * If this is not possible in your code, you actually have to say
 * .js here, not .graphql, because the file will be called .js after
 * build.
 */
import generated from './generated';

console.log(generated);

您将看到schema是文件构建前步骤的内容的字符串。

现在它可以作为typeDefs用于makeExecutableSchema

代码语言:javascript
复制
import { makeExecutableSchema } from 'graphql-tools';
import typeDefs from './generated';
import resolvers from './resolvers';

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

如果您使用了一个绑定程序和/或转换程序,那么还需要做一些额外的工作,以确保文件也通过这些工具运行。我使用过这种方法的项目只使用babel,问题是:

  1. 使用npm代替babel的-watch选项来运行构建脚本
  2. (可以并行完成)
    • 在所有源文件.js上运行babel
    • 在所有.graphql文件上运行自定义脚本,其中:
      1. 将相关代码添加到文件中,使其成为有效的js (内存中)
      2. 以编程方式对结果运行babel
      3. 使用.js扩展将其保存到构建目标。

但是,要小心处理大文件,因为使用此方法将它们加载到内存中!

但是要小心,因为这种方法不适用于绑定程序,为此您必须在运行绑定程序之前对文件进行转换(并且在某种程度上仍然保留旧版本,可能是通过以不同的方式命名转换后的版本,并在运行绑定器之后删除它),或者查找/创建一个为您完成此工作的插件。下面是我找到的一些选项(快速谷歌搜索):用于webpack包裹

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52935217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档