Search code examples
typescriptmodulegraphqlgraphql-tag

How to declare a module to do named imports?


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. :)


Solution

  • 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';