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

Struggling with the transformation: Failed to find import "child_process" in TypeScript

I encountered an issue when trying to run my simple TypeScript project. I am receiving the following error: 'Error while transforming Could not resolve import "child_process".' You can see the error in this screenshot. This error occurs in my tsc ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

Generate a basic collection of strings from an object

Looking at this object structure Names = [ { group: 'BII', categories: null }, { group: 'GVL', categories: [] } ]; I ...

Hide the FormArray in a Reactive Form if it is not populated or cannot be determined

As a newcomer to Angular 4, I've embarked on my first project and started learning the ropes. I have devised a Reactive Form to showcase a form structure that looks like this: Form (FormGroup) | --> aggLevels (FormArray) | --> ...

Establish a connection to the ActiveMQ broker utilizing STOMP protocol in an Ionic application

I've recently received an Ionic + Capacitor app that is primarily meant to run on the Android platform. My current task is to incorporate communication with a remote ActiveMQ broker into the app. To achieve this, I utilized the STOMP JS library which ...

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

Retrieve a specific element from an array list

Hey everyone, I'm facing a problem in my application where I need to extract a specific value from my array and display it in a table for users to see. Check out the code snippet below: Here's my mock data: { "Data": "2020-0 ...

When working with formControlName in Angular Material 2, the placeholder may overlap the entered value

After updating my application with angular-cli to angular/material (2.0.0-beta.11) and angular (4.4.4), I noticed that every placeholder in the material input fields overlaps the value when provided with formControlName in reactive forms. However, when usi ...

Implementing Global Value Assignment Post Angular Service Subscription

Is there a way to globally assign a value outside of a method within my app component? This is how my service is structured: import { NumberInput } from '@angular/cdk/coercion'; import { HttpClient } from '@angular/common/http'; import ...

Exploring the World of Angular: Abstracts and Data Transformations

Facing a perplexing issue with a component that is based on an abstract class, or at least that's my assumption. There are multiple sibling components rendered using *ngFor based on an array length. These siblings, derived from an abstract class, rec ...

Avoid including any null or undefined values within a JSON object in order to successfully utilize the Object.keys function

My JSON data structure appears as follows: { 'total_count': 6, 'incomplete_results': false, 'items': [ { 'url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2', 'repository_url' ...

How to pass props to customize styles in MUI5 using TypeScript

Currently, I'm in the process of migrating my MUI4 code to MUI5. In my MUI4 implementation, I have: import { createStyles, makeStyles } from '@material-ui/core'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; ty ...

Ways to utilize the scan operator for tallying emitted values from a null observable

I'm looking for an observable that will emit a count of how many times void values are emitted. const subject = new Subject<void>(); subject.pipe( scan((acc, curr) => acc + 1, 0) ).subscribe(count => console.log(count)); subject ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

Is there a method to indicate not using the watch feature through the command line in TSC?

Is it possible to disable the watch mode in the Typescript compiler cli through command line, instead of relying on the configurations from tsconfig.json? ...

"Ensuring function outcomes with Typescript"Note: The concept of

I've created a class that includes two methods for generating and decoding jsonwebtokens. Here is a snippet of what the class looks like. interface IVerified { id: string email?: string data?: any } export default class TokenProvider implements ...