5

I'm using graphql-tag. My files are like that.

./operation.graphql

Query User {
   ...
}

./test.ts

import { User } from './operation.graphql'; /// Module ''*.graphql'' has no exported member 'User'.

./index.d.ts

declare module '*.graphql' {
    import { DocumentNode } from 'graphql';

    const value:DocumentNode;

    export default value;
}

A application is work well, but I want to prevent that error.

When I do default import is work well, but as you see, I got an error at named imports.

How to declare this? Thanks. :)

left click
  • 894
  • 10
  • 21

1 Answers1

7

If the name of the export you want is different for each GraphQL file, TypeScript won't parse your GraphQL file to figure it out automatically. Either you need a separate module declaration for each GraphQL file (and you'll need to set your baseUrl and paths so you can use non-relative imports, or it might work to put a d.ts file alongside each GraphQL file instead of using declare module, I'm not sure):

declare module 'operation.graphql' {
    import { DocumentNode } from 'graphql';

    export const User: DocumentNode;
}

Or you can give up and let all the GraphQL files be of type any:

declare module '*.graphql';
Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75
  • Thanks. :) it's helpful! – left click Aug 31 '18 at 14:16
  • I ran into this today, and ended up using [@graphql-codegen/typescript-graphql-files-modules](https://the-guild.dev/graphql/codegen/plugins/typescript/typescript-graphql-files-modules) to generate the types, with named exports, from the gql docs. – x1a4 Jan 21 '23 at 18:04