Edgar
Edgar

Reputation: 6856

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 ?

Upvotes: 11

Views: 10487

Answers (2)

Mir-Ismaili
Mir-Ismaili

Reputation: 16978

The solution provided by @CalebFaruki (and already here) works. But the only thing I needed is to add graphql.d.ts file (anywhere in my src directory):

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

Without compilerOptions.typeRoots and files in tsconfig.json.

Upvotes: 2

Caleb Faruki
Caleb Faruki

Reputation: 2725

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.

Upvotes: 10

Related Questions