Is there a way to configure tsconfig so that it can properly recognize ".graphql" files and aliases when they are imported into components?

Currently, I have encountered an issue where including "graphql" files in my components is leading to TypeScript errors due to unrecognized import pathing. Despite the error, the functionality works as expected.

import QUERY_GET_CATS from "@gql/GetCats.graphql";

The error message received is: TS2307: Cannot find module '@gql/GetCat.graphql' or its corresponding type declarations

Below is my tsconfig:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "*": [
        "./*"
      ],
      "@gql/*": [
        "./api/gql/*"
      ]
    },
    "lib": ["dom", "dom.iterable", "esnext"],
    "strict": true,
    "noUnusedLocals": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "isolatedModules": true,
    "jsx": "preserve",
    "downlevelIteration": true,
    "allowJs": true,
    "skipLibCheck": true,
    "resolveJsonModule": true
  },
  "exclude": [
    "cypress",
    "coverage",
    "node_modules",
    "build",
    "dist",
    "out",
    ".next",
    "next.config.js",
    "./**/*.js",
    "./**/*.jsx",
    "./**/*.scss"
  ],
  "include": [
    "next-env.d.ts",
    "./**/*.ts",
    "./**/*.tsx"
  ]
}

Here is my eslintrc configuration:

const path = require('path');

// Your eslint config object here...

A couple of notes: - Adding "./**/*.graphql" to the "include" array did not resolve the issue. - Other aliases are functioning correctly, except for the "graphql" ones.

Answer №1

Due to the fact that these files utilize gql syntax, which is not native to Typescript, it is necessary to declare them as an ambient module in a type definitions file, as outlined in the typescript documentation.

documentNode.d.ts

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

  const value: DocumentNode;
  export = value;
}

Additionally, you must include "./**/*.graphql" in the include section of your tsconfig file.

It's important to note that this serves as a placeholder allowing you to import the files within your codebase without extracting any type information from their contents. There is a tool developed by the creators of graphql code generator known as TypedDocumentNode, which enables you to incorporate fully typed DocumentNodes into your project, albeit I have not personally tested it so results may vary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locate and retrieve the item that appears most often in a given array

In order to determine the mode of an array consisting of integer numbers only, I must create a function named findMode. If the array is empty, the function should return 0. Otherwise, it should return the element that occurs most frequently in the array. I ...

Utilize the imported function from <Script> within NextJS

When working with vanilla JS, I am able to include a script like this: <head> <script src="https://api.site.com/js/v1/script.js"></script> </head> and then create an instance of it using: const fn = ScriptJS(); I can t ...

Typescript Error: Trying to access a property that is undefined

I am a beginner in typescript and believe that the issue I am facing is related to typescript. Currently, I am working on an Ionic app where I have a function setwall() being called from home.html. The setwall() function is defined in home.ts. However, whe ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...

Tips on displaying a spinner only when data is retrieved from an Http service

How can I ensure that a spinner is only shown during an HTTP service call and dismissed when my component receives data? To address this issue, I implemented a cache service to store data fetched from the HTTP service for future use. However, I want to sh ...

Angular 13: Issue with displaying lazy loaded module containing multiple outlets in a component

Angular version ^13.3.9 Challenge Encountering an issue when utilizing multiple outlets and attempting to render them in a lazy module with the Angular router. The routes are being mapped correctly, but the outlet itself is not being displayed. Sequence ...

Exploring nested JSON objects within an array using ngFor directive

My application uses Angular 6 and Firebase. I am trying to showcase a list of all appointments. Below is my approach: service.ts getRDV() { this.rdvList = this.firebase.list('/rdv'); return this.rdvList; } Model: export class RDV { key: ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...

Printing error stack that includes the source from the source map

I've been trying to take advantage of the native support for source maps in Node, but I'm having trouble getting them to work when printing errors to the console. Despite running node with --enable-source-maps and using the source-map-support pa ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Guide on retrieving the interface property name or key name as a string in Typescript

Currently, I am utilizing the API of Slack and encountering situations where I send JSON requests containing strings that return as property names later on. I want to create an interface where I can send one of its property names as a string and receive t ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble. I have three folders that need to redirect HTML based on the option chosen. In Angular, I cre ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

I am trying to figure out how to dynamically set the deployUrl during runtime in Angular

When working with Angular, the definition of "webpack_public_path" or "webpack_require.p" for a project can be done in multiple ways: By setting the deployUrl in the .angular-cli.json file By adding --deployUrl "some/path" to the "ng build" command line ...

Accessing information necessitates two separate subscriptions

I am posting this inquiry in order to enhance my understanding. Below is an excerpt from my service: export class HomeService { private generalstatistics = new ReplaySubject<object>(); constructor( private http: HttpClient ) { this ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...