Having trouble resolving module paths while using typescript with eslint

In my file app.spec.ts, I am encountering an issue with the following import statement:

import app from './app';

This is resulting in a Typescript error:

2:17  error  Unable to resolve path to module './app'  import/no-unresolved

Although ./app.ts does exist, the error persists until I compile the .ts file into a .js file. Once compiled, the error disappears.

Since eslint should support Typescript, it should ideally resolve modules using the .ts extension rather than the .js extension.

I have also included Typescript information in my eslint config file:

"parser": "@typescript-eslint/parser",
"parserOptions": {
    "project": "./tsconfig.json"
}

Is there a way to configure eslint so that it attempts to resolve modules using the .ts extension instead of the .js extension?

EDIT #1

Below is the content of app.ts:

import bodyParser from 'body-parser';
import express from 'express';
import graphqlHTTP from 'express-graphql';
import { buildSchema } from 'graphql';

const app = express();

const schema = buildSchema(`
    type Query {
        hello: String
    }
`);
const root = { hello: () => 'Hello world!' };

app.use(bodyParser());
app.use('/graphql', graphqlHTTP({
    schema,
    rootValue: root,
    graphiql: true,
}));

export default app;

Answer №1

To customize the ESLint module import resolution, include the following code snippet in your .eslintrc.json configuration file:

{
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  },
  // ...
}

For further details on resolvers, refer to: https://github.com/benmosher/eslint-plugin-import#resolvers.

Answer №2

After encountering a similar issue, I managed to resolve it by incorporating the typescript plugin into my .eslintrc file and utilizing the extends feature in .eslintrc

  extends: [
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
  ],

Answer №3

This method was the key to solving my issue.

Start by downloading and installing this specific package:

yarn add -D eslint-import-resolver-typescript

Next, make sure to include the following code snippet in your .eslintrc file so that ESLint can access the alias configurations from your tsconfig.json:

{
  "settings": {
    "import/resolver": {
      "typescript": {}
    },
  },
}

Answer №4

Here is the solution that works best for me:

.eslintrc.js

{
    ...
    settings: {
        ...
        'import/resolver': {
            node: {
                extensions: ['.js', '.jsx', '.ts', '.tsx'],
                moduleDirectory: ['node_modules', 'src/'],
            },
        },
    }
}

Answer №5

For me, all I needed to do was make a simple adjustment:

import { MakeOptional, MakeRequired } from 'type-fest';

became

import type { MakeOptional, MakeRequired } from 'type-fest';

Answer №6

When incorporating "eslint": "6.8.0" and "typescript": "3.8.3", in addition to including the following configuration in your .eslintrc:

"settings": {
  "import/resolver": {
    "node": {
      "paths": ["src"],
      "extensions": [".js", ".jsx", ".ts", ".tsx"],
    }
  },
}

It is also necessary to append this line to your tsconfig.json within the compilerOptions:

"compilerOptions": {
  ...
  // Specifying the base directory for resolving non-relative module names.
  "baseUrl": "src",
  ...
}

Answer №7

After making the recommended changes to your .eslintrc and tsconfig.json files, if you are still facing the issue, the best course of action would be to restart your vscode editor.

Answer №8

For individuals utilizing the babel-module, simply include the extensions parameter as shown below:

      "babel-module": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"],
        "alias": {
          "app": "./app"
        }
      }

Answer №9

When faced with the barking of both ts and eslint, I found myself having to make adjustments to my .eslintrc configuration file:

{ 
    ...
    "rules": {
        ....
        "import/extensions": "off"
    },
    "settings": {
        ....
        "import/resolver": {
            "node": {
                "extensions": [".js", ".jsx", ".ts", ".tsx"]
            }
        }
    }
}

Answer №10

While incorporating locale files into Angular (for example,

import localeEn from '@angular/common/locales/en';
), I encountered the need to include the .mjs extension.

Below is a snippet from my .eslintrc.json:

  ...
  "extends": [
    ...
    "plugin:import/recommended",
    "plugin:import/typescript",
    ...
  ],
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".ts", ".mjs"]
      }
    }
  },
  "rules": {
    ...
  }
  ...

Correction:

Upon importing HttpClient or HttpClientModule, the error resurfaced. I realized that including the .d.ts extension in the list resolved the issue, which also seemed more logical than using .mjs (which is now unnecessary).

Therefore, here is the updated version of my .eslintrc.json:

 ...

  {
    "files": ["*.ts"],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
      "project": ["tsconfig.json"],
      "createDefaultProgram": true
    },
    "settings": {
      "import/resolver": {
        "node": {
          "extensions": [".ts", ".d.ts"]
        }
      }
    },
    "extends": [
      "eslint:recommended",
      "plugin:import/recommended",
      "plugin:import/typescript",
      "plugin:@typescript-eslint/recommended",
      "plugin:@angular-eslint/recommended",
      "plugin:@angular-eslint/ng-cli-compat",
      "plugin:@angular-eslint/ng-cli-compat--formatting-add-on",
      "plugin:@angular-eslint/template/process-inline-templates"
    ],
    "rules": {
      ...
    }
  }

  ...

(I utilize @angular-eslint, but your extends list may differ)

Answer №11

To get started, make sure to include the following line under extends:

"extends": [
    "airbnb-base",
    "plugin:import/typescript"
 ],

Next, add the rules section as shown below:

"rules": {
        "import/extensions": [
            "error",
            "ignorePackages",
            {
                "ts": "never"
            }
        ]
    }

Answer №12

My experience involved an issue with ESLint not being able to recognize the types imported from DefinitelyTyped (@type/ packages). To solve this, I had to explicitly specify the location of these types in my .eslintrc file like so:

"import/resolver": {
    "typescript": {},
    "node": {
        "extensions": [".js", ".ts"],
        "paths": ["node_modules/", "node_modules/@types"]
    }
},

I also included "typescript": {} to enable the use of configurations from my tsconfig.json file. Additionally, I made sure to have the

eslint-import-resolver-typescript
package installed for proper functionality.

Answer №13

In my experience with the ts monorepo setup, I encountered a situation where I was not receiving any lint errors in my IDE and all aliases were being resolved correctly. However, when I ran eslint on one of the projects, I started seeing the following error:

error  Unable to resolve path to module

It is crucial to provide eslint with the path to each package's tsconfig file.

To summarize, for those working with TS, aliases, and monorepos:

  • Install
    eslint-import-resolver-typescript
  • Add the following settings to your eslintrc.js (this will assist both the IDE and eslint in understanding aliases and other configurations):
'import/resolver': {
      node: {
        paths: 'packages/*/src',
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
      typescript: {
        alwaysTryTypes: true,
        project:[
         path.resolve(__dirname, '.tsconfig.json'), // root tsconfig
         path.resolve(__dirname, './packages/projA/tsconfig.json'),
         path.resolve(__dirname, './packages/projB/tsconfig.json'),
         /* ...rest of projects path to its tsconfig */
        ],
      },
  • Add the following extends to your eslintrc.js:
{
 ...,
   'plugin:import/recommended',
   'plugin:import/typescript',
}

  • Include the following plugins in your eslintrc.js:
  plugins: ['@typescript-eslint', ..., 'import'],
  • Update the parserOptions in your eslintrc.js (matching the settings) to help eslint:
        project: [
          path.resolve(__dirname, '.tsconfig.json'), // root tsconfig
          path.resolve(__dirname, './packages/projA/tsconfig.json'),
          path.resolve(__dirname, './packages/projB/tsconfig.json'),
          /* ...rest of projects path to its tsconfig */
        ],

Answer №14

In order to make it work, I included the typescript import for extension and disabled imports in the rules:

"extends": {
    "plugin:import/typescript"
},
"rules": {
    "import/extensions": "off"
}

Answer №15

If there is a need to also support child directories, for example:

  1. src/components/input => components/input
  2. src/api/external/request => external/request

    "settings": {
      "import/resolver": {
        "node": {
          "paths": ["src", "src/api"],
          "extensions": [".js", ".jsx", ".ts", ".tsx"]
        }
      }
    }
    

This example works with eslint version 6.1.0

Answer №16

I found a solution by adding the eslint-import-resolver-node package:

yarn add -D eslint-import-resolver-node
# or
npm install eslint-import-resolver-node --save-dev

Answer №17

By incorporating the following setup in my .eslintrc.js configuration, I was able to successfully resolve this issue:

   settings: {
      'import/parsers': {
         '@typescript-eslint/parser': ['.ts', '.tsx'],
      },
      'import/resolver': {
         node: {
            extensions: ['.js', '.jsx', '.ts', '.tsx'],
         },
         typescript: {
            alwaysTryTypes: true,
            project: ['**/tsconfig.json'],
         },
      },
   }

Additionally, remember to install the package with the command:

npm i eslint-import-resolver-typescript

For more information, refer to the documentation at https://www.npmjs.com/package/eslint-import-resolver-typescript

Answer №18

After encountering an error, I discovered that the issue stemmed from using eslint-config-airbnb, which was not compatible with typescript. To resolve this issue, I followed the recommendation provided in this answer and installed eslint-config-airbnb-typescript. The necessary setup instructions can be found on the npm page, which includes adjusting your eslint config to incorporate it and linking it to your typescript configuration.

If you utilized create-react-app for app setup, you may have encountered an eslintConfig section within your package.json file. It's important to have only one ESLint configuration. If you decide to create an .eslintrc file for setting up typescript linting, remember to delete the block from package.json and transfer any configurations from there to the single config file.

Answer №19

The problem stemmed from incorrect path resolution in the source folder. To fix this issue, I included the parent directory of the source folder in the paths.

Original Code:

"settings": {
  "import/resolver": {
    "node": {
      "extensions": [".js", ".jsx", ".ts", ".tsx"],
      "paths": ["src"]
    }
  }
}

I made the following adjustment:

"settings": {
  "import/resolver": {
    "node": {
      "extensions": [".js", ".jsx", ".ts", ".tsx"],
      "paths": ["src", "client/src"]
    }
  }
}

Explanation: The addition of the "client/src" path enables the resolver to accurately locate files within that specific directory when importing or resolving modules. This update effectively resolved the path resolution challenge encountered in my project.

(Optional: If relevant, specify where the "settings" block should be inserted in your project's configuration file, such as webpack.config.js, tsconfig.json, etc.)

I trust this solution can assist others grappling with a similar issue!

Answer №20

This code snippet for 2023 has been a lifesaver

  env: { browser: true, es2020: true, node: true },
  extends: [
    'plugin:react/recommended',
    'airbnb',
    'airbnb-typescript',
    'airbnb/hooks',
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react-hooks/recommended',
    'plugin:import/recommended',
    'plugin:import/typescript',
    'prettier',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json',
    ecmaVersion: 2018,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
    // Airbnb disable eslint-import-resolver-typescript
    // See: https://github.com/iamturns/eslint-config-airbnb-typescript#why-is-importno-unresolved-disabled
    // But, To support the tsconfig baseUrl and paths for aliasese that we uses,
    // you need this package
    // See configuration here
    // https://github.com/alexgorbatchev/eslint-import-resolver-typescript#installation

    'import/parsers': {
      '@typescript-eslint/parser': ['.ts', '.tsx'],
    },
    'import/resolver': {
      typescript: {
        alwaysTryTypes: true,
      },
    },

Answer №21

After clearing the eslint cache, everything fell into place perfectly for me. (Our yarn script looks like this:

"lint:eslint": "eslint . --cache --cache-location '../../eslintcache/' --format stylish"

.)

Answer №22

Despite dedicating numerous hours to experimenting with various methods on this website, unfortunately none of them resolved my issue. The complexity of my project necessitates the use of multiple tsconfig files.

To address this, I incorporated

eslint-import-resolver-typescript
into my project:

npm install eslint-import-resolver-typescript

Subsequently, I made the following modifications to my eslintrc file:

    settings: {
        "import/resolver": {
            typescript: {
                project: ["./path/to/config.json", "./path/to/config2.json", "./path/to/config3.json"] // Path to your tsconfig.json file
            }
        }
    },

Answer №23

  1. Include the following code snippet in the extends section:

    "extends": [
      "airbnb-typescript",
    ]
    
  2. Insert the following code block into the parserOptions:

    "parserOptions": {      
       "project": "./tsconfig.json"
     },
    
  3. Make sure to add the dev module by running this command:

    npm i --save-dev eslint-config-airbnb-typescript 
    

Answer №24

Genius individuals can effortlessly tackle this with a single line of code in 2022:

"rules": {
  "import/extensions": [ "error", "ignorePackages", { "": "never" } ]
}

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

Angular 2 failing to show "mandatory" dialogue on the form

I am new to Angular 2 and have created a form using Angular 2 and bootstrap. When I click on the text field and then move the mouse elsewhere, the box turns red, which is working correctly. However, when I click on the submit button with an empty form, it ...

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

Patience is necessary as we await the initialization of the lazily loaded

I'm dealing with a scenario where I have a button triggering an onClick handler. In the onClick function, the first action is: if (this.state.lazyLoadedData === undefined) { await this.loadData(); } The issue arises when I click the button rapid ...

How can I resolve a promise that is still pending within the "then" block?

Here is a piece of code that I have written: fetch(`${URL}${PATH}`) .then(res => { const d = res.json(); console.log("The data is: ", d); return d; }) When the code runs, it outputs The data is: Promise { <pending> ...

Adding up elements in a vector using TypeScript

Is there a way to calculate the sum of values based on the name without repetition in "dataGrf"? I've tried various methods but am facing difficulties. Here is a brief example below to help illustrate what I'm attempting to achieve. Note: Please ...

Combining existing CSS classes with node labels in Cytoscape JS for Angular: A Guide

My project follows a consistent CSS theme, but the node's CSS style doesn't match. I'm looking to adjust the label colors in the CSS based on whether it's day mode or night mode. How can I accomplish this? this.cy = cytoscape({ con ...

What is the equivalent of defining conditional string types in Typescript similar to flow?

type UpsertMode = | 'add' | 'update' | 'delete'; interface IUpsertMembers { mode: UpsertMode; } const MagicButton = ({ mode: UpsertMode }) => { return ( <button>{UpsertMode}</button> ); } const Upse ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

The custom error handling middleware in Express.js appears to be ineffective for certain error cases

The custom error handler code snippet provided below: export const errorHandler: ErrorRequestHandler = (err, _, res) => { if (err instanceof HttpError) { res.status(err.statusCode).json({ message: err.message }); return; } res.st ...

Ways to retrieve a URL from the assets folder

I need to establish a baseUrl for my backend requests within the assets folder. For this, I have created a server configuration file named config.json { "backendServer": { "protocol": "http", "host": " ...

NestJs encountering issues with reading environment variables

I used the instructions from the Nest documentation to set up the configuration, however, it's not functioning correctly. app.module.ts @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), TypeOrmModule.forRoot(config), AuthMo ...

Resolving conflicts between class names for React-Icons in Typescript and Javascript (Answering my

After working with React in JavaScript, I made the switch to NextJs with TypeScript. I encountered an issue when trying to import react-icons such as BiUser. In React, adding a className to icons worked smoothly, but in TypeScript, it resulted in an error ...

Ways to effectively utilize an interface incorporating props.children and other property varieties

Currently working on a project with Next.js and Typescript. In order to create a layout component, I defined the following interface: export interface AuxProps { children: React.ReactNode; pageTitle: 'string'; } The layout component code sn ...

Removing a targeted element from an array in Angular

After receiving a JSON array object in Angular using TypeScript, I am attempting to remove a specified object from it. However, my attempts at deletion have been unsuccessful. addCategorySub(categorySub: CategorySubModel, index: number) { categorySub.id ...

typescript support for the appwrite web sdk

Currently, I am experimenting with the demo-todo-with-react project using TypeScript. I encountered an issue while creating api.tsx based on api.js. The error message states that "Type '{database: Database; account: Account;}' is not assignable t ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

Trouble encountered while launching a TypeScript React app using Docker Compose

Currently, I am working on setting up a typescript monorepo with a nodejs backend and a create-react-app frontend. My goal is to have the frontend running smoothly in a container while being able to make code changes on the host machine that automatically ...

Using Typescript with MongoDB's JSON schema

Exploring the usage of MongoDB's $jsonschema validator with npm's json-schema-to-typescript has me intrigued. However, I've noticed that MongoDB utilizes bsontype instead of type, which may introduce additional differences that are currently ...

What is the command line method for running ESLint in flat configuration?

When using the flat config for eslint.config.js, how can I lint *.js files recursively from the command line? 1 In the past with eslintrc.js or eslintrc.json, I have used npx eslint . --ext .js, as mentioned here. Up until now, it has always worked withou ...

The PDF can be accessed from the console but the network tab is not visible

import { axiosInstances } from "./axiosInstanc" interface upladPdfPayload { name: string; pdf: File } export const uploadPdfApi = async (payload: upladPdfPayload) => { try { console.log(payload); const res = await a ...