如何将一个GraphQL文件导入到TypeScript中?

8
我想导入一个graphql文件,但是出现了错误。
从"./schema/schema.graphql"导入typeDefs;
10 import typeDefs from "./schema/schema.graphql";
                        ~~~~~~~~~~~~~~~~~~~~~~~~~

    at createTSError (C:\Users\darkc\Desktop\New folder (2)\server\node_modules\ts-node\src\index.ts:750:12)
    at reportTSError (C:\Users\darkc\Desktop\New folder (2)\server\node_modules\ts-node\src\index.ts:754:19)
    at getOutput (C:\Users\darkc\Desktop\New folder (2)\server\node_modules\ts-node\src\index.ts:941:36)

如何将graphql文件导入到typescript中?

你无法在没有 Babel 或其他类型的转译器/构建工具的情况下进行导入。你可以使用 https://www.npmjs.com/package/babel-plugin-import-graphql。 - Tsvetan Ganev
我安装了 babel-plugin-import-graphql,但仍然出现错误。 - S22
2个回答

8

为了使导入工作,您需要告诉TypeScript一个.graphql文件是什么。这不是TypeScript OOTB支持的文件类型。为此,请在您的项目中创建一个类型定义文件,例如graphql.d.ts。该文件应包含以下声明或类似内容:

declare module '*.graphql' {
  import { DocumentNode } from 'graphql'
  const Schema: DocumentNode

  export = Schema
}

个人而言,我更喜欢简写扩展名*.gql。只需更改declare module表达式中的字符串值即可实现。

最后,您需要告诉TypeScript在您的TypeScript配置tsconfig.json文件中包含您的自定义类型定义:

{
  "compilerOptions": {
    ...
    "typeRoots": ["node_modules/@types", "src/@types"],
  },
  "files": ["src/@types/graphql.d.ts"],
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

记录一下,我从以下文章中获取了这个答案:https://dev.to/open-graphql/how-to-resolve-import-for-the-graphql-file-with-typescript-and-webpack-35lf。但你会发现大多数解决方案实际上都涉及相同的步骤。


1
有没有办法从一个单一文件(而不是文件夹)中导入/导出多个查询? - Himanshu Rawat
1
感谢您提供这个准确的答案!对于NextJS开发人员:您只需要在src目录中创建上述graphql.d.ts声明文件(例如:src/types/graphql.d.ts),因为Next会自动加载所有*.d.ts文件,如果使用NextJS 10+则无需添加到tsconfig.json。 - Marty McGee

0

@CalebFaruki 提供的解决方案(已经here)可行。但我需要做的唯一一件事就是添加graphql.d.ts文件(可以放在我的src目录中的任意位置):

declare module '*.graphql' {
  import { DocumentNode } from 'graphql'
  const Schema: DocumentNode
  export = Schema
}

tsconfig.json 中没有 compilerOptions.typeRootsfiles


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接