'How to import a graphql file to typescript?

I want to import a graphql file but I get an error

import typeDefs from "./schema/schema.graphql";

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)

How to import a graphql file to typescript ?



Solution 1:[1]

You need to tell TypeScript what a .graphql file is in order for the import to work. This is not a file type that is supported OOTB in TypeScript. To do so, create a type definition file such as graphql.d.ts in your project. The file should contain the following declaration or somethings similar:

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

  export = Schema
}

Personally, I prefer the shorthand extension *.gql. To do that, simply change the string value in the declare module expression.

Lastly, you will need to tell TypeScript to include your custom type definition in your TypeScript configuration tsconfig.json file:

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

For the record, I pulled this answer from the following article: https://dev.to/open-graphql/how-to-resolve-import-for-the-graphql-file-with-typescript-and-webpack-35lf. But you'll find that most solutions involve the same steps effectively.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caleb Faruki