首页 > 解决方案 > 将 .graphql 中的类型导入 .js 文件

问题描述

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

但我想做的是将一些typesgenerated.graphqlPrisma 导入到.js文件中。

例如:

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

"""generated.graphql file"""
type ItemWhereInput { ... }

type ItemConnection { ... }

...

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

// 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]; 

这样我就可以在其他地方调用makeExecutableSchemagraphql-tools使用这些类型

// 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,
};

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

谢谢。

标签: javascripttypesimportgraphqlprisma

解决方案


您应该能够执行以下操作:

在构建步骤中,首先,将generated.graphql文件转换为 js 文件

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

这样,您可以将文件作为开发代码中的 js 文件导入:

// 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

import { makeExecutableSchema } from 'graphql-tools';
import typeDefs from './generated';
import resolvers from './resolvers';

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

如果您使用捆绑器和/或转译器,则必须完成一些额外的工作,以确保文件也可以通过这些工具运行。我使用这种方法的项目只使用了 babel,这是一个问题:

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

不过要小心大文件,因为它们是用这种方法加载到内存中的!

但请注意,因为这种方法不适用于捆绑器,为此您必须在运行捆绑器之前转换文件(并且以某种方式仍然保留旧版本,可能通过以不同的方式命名转换后的版本并在运行捆绑器后将其删除),或查找/创建一个插件为您完成这项工作。以下是我找到的一些选项(快速谷歌搜索):对于webpackParcel


推荐阅读