Git Product home page Git Product logo

eslint-import-resolver-typescript's People

Contributors

alexgorbatchev avatar billnbell avatar bradzacher avatar brettz9 avatar chenxinyanc avatar chrisblossom avatar dnalborczyk avatar f3n67u avatar gcangussu avatar github-actions[bot] avatar hanseo0507 avatar jhoch avatar joakimbeng avatar jounqin avatar klippx avatar lgtm-com[bot] avatar lsmurray avatar marvinhagemeister avatar okuramasafumi avatar oliverjash avatar pekala avatar rbong avatar renovate[bot] avatar rialgar avatar sanderson-ut avatar stefanprobst avatar sukkaw avatar teoxoy avatar thatsmydoing avatar vkrol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

eslint-import-resolver-typescript's Issues

Licence ?

Hi, could you please publish a valid license?

Much appreciate it
Natan

directory starting with a dot does not work

The following example:

{
  "settings": {
    "import/resolver": {
      "typescript": {
        "directory": "./packages/*/tsconfig.json"
      }
    }
  }
}

doesn’t work, globSync() (from tiny-glob) resolves nothing. It works without the leading ./, i.e. packages/*/tsconfig.json.

(I spent an hour trying to figure out why the heck I’m still getting unresolved import errors even after changing my configuration to exactly match the examples. ☹️)

[import/extensions] Missing file extension "ts/tsx" for "..."

.eslintrc.js

module.exports = {
    env: {
      browser: true,
      es6: true,
      node: true,
    },
    extends: [
      'plugin:react/recommended',
      'airbnb',
      'airbnb/hooks',
      "plugin:@typescript-eslint/eslint-recommended",
      "plugin:@typescript-eslint/recommended",
      "plugin:@typescript-eslint/recommended-requiring-type-checking",
      "plugin:import/errors",
      "plugin:import/warnings",
      "plugin:import/typescript",
    ],
    globals: {
      Atomics: 'readonly',
      SharedArrayBuffer: 'readonly',
    },
    parser: '@typescript-eslint/parser',
    parserOptions: {
      project: "./tsconfig.json",
      ecmaFeatures: {
        jsx: true,
      },
      ecmaVersion: 2018,
      sourceType: 'module',
    },
    plugins: [
      'react',
      '@typescript-eslint',
    ],
    settings: {
      "import/parsers": {
        "@typescript-eslint/parser": [".ts", ".tsx"]
      },
      "import/resolver": {
        "typescript": {}
      }
    },
    rules: {
      "@typescript-eslint/interface-name-prefix": "off",
      "@typescript-eslint/no-explicit-any": "off",
      "@typescript-eslint/explicit-function-return-type": "off",
      "import/no-unresolved": "error",
      "import/no-default-export": "error",
      "import/prefer-default-export": "off",
      "react/no-array-index-key": "off",
      "react/jsx-filename-extension": [1, { "extensions": [".jsx", ".tsx"] }],
      "react-hooks/exhaustive-deps": "off",
    },
  };

.tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
    "target": "esnext",
    "baseUrl": ".",
    "paths": {
      "@lyon/components/*": ["components/*"],
      "@lyon/pages/*": ["pages/*"],
      "@lyon/scoped-models/*": ["scoped-models/*"],
      "@lyon/utils/*": ["utils/*"],
    },
  },
  "exclude": ["node_modules"],
  "include": ["**/*.ts", "**/*.tsx"]
}

Screen Shot 2020-01-07 at 4 17 11 PM

As you can see, the linter throws an error but the editor can properly resolve the module. Any solutions?

[import/no-unresolved] not working in our mono-repo from 2.0.0

We recently upgraded to Typescript 3.7 and updated all eslint + prettier related packages. Moving from [email protected] to [email protected] is leading to more import/no-unresolved errors showing up for paths configured in tsconfig.json in the sub-packages.

Our structure

.
├── ...
├── .eslintrc.js
├── packages
│   ├── a
│   │   ├── .eslintrc.js
│   │   ├── tsconfig.json
│   │   └── package.json
│   └── b
│       ├── .eslintrc.js
│       ├── tsconfig.json
│       └── package.json
├── ...
├── package.json
├── lerna.json

We're using multiple .eslintrc.js in each directory since the projects are cross platform (node/browser) and have different environments & configurations.

Configs

// .eslintrc.js
module.exports = {
  // ...
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
  },
  plugins: ['import'],
  rules: {
    // ...
    /** Show errors for un-resolved imports */
    'import/no-unresolved': 'error',
    // ...
  },
  settings: {
    'import/parsers': {
      '@typescript-eslint/parser': ['.ts', '.tsx'],
    },
    'import/resolver': {
      typescript: {
        directory: ['packages/*/tsconfig.json'],
      },
    },
  },
};
// .eslintrc.js
const { resolve } = require('path');

module.exports = {
  settings: {
    'import/resolver': {
      typescript: {
        directory: resolve(__dirname, 'tsconfig.json'),
      },
    },
  },
};

What we've tried

  • Having a single setting in the root level with packages/*/tsconfig.json
  • Having a single setting in the root level with array of actual file paths to the tsconfig directory.
  • Both the above with explicit setting in the package (a/b) level setting with directory: resolve(__dirname, 'tsconfig.json'),

We downgraded back to v1.1.1. 😅

Can you help us out? Happy to provide more information as required.

Bug: Wrong path resolutions if used to lint several projects

Bug

Current Behavior

If this library used to lint several projects at once - only first project paths are taken into account (and they are also exposed to other projects)

Desired Behavior

Each project paths should be resolved according to this project tsconfig.json file.

Requirements to reproduce this bug

  1. There should be at least two folders with "subprojects" inside root folder, for example "app1" and "app2"
  2. Each subproject folder should contain it's own tsconfig.json and .eslintrc.js file
  3. Each .eslintrc.js file should contain it's own settings for import/resolver, which points to current subproject folder (or tsconfig.json file), e.g.:
    settings: {
        'import/resolver': {
            typescript: {
                directory: __dirname
            }
        }
    }
  1. Run eslint . --ext .ts from the root folder to validate all subrojects at once

Suggested Solution

Currently in source code if this library function initMappers invokes only once at the very start. To fix this bug this function should be invoked again if new set of options is passed (this situation will happen if there is several eslintrc configs with different import/resolver settings.

Workarounds

There is two possible workarounds, which can be used till this bug will be fixed:

  1. Run eslint for each project separately
  2. Use single .eslintrc file at the root folder which will contain references to tsconfig.json files in each project.

Fails when importing with .js/.jsx extensions

The TypeScript compiler is able to resolve imports from identifiers suffixed with .js and .jsx back to their .ts/.tsx counterparts. However this package currently can't handle this. This creates a mismatch between the resolution implemented here and tsc's.

Writing imports with .js/.jsx suffixes is useful. When you are targeting spec compliant ES6 modules, it allows you to not depend of another build step besides the compilation done with tsc.

For example, assume there is a bar.ts file that exports a function foo. Then, the module

import { foo } from './bar.js';
function baz(): string { foo(); return 'hello' }

Will be compiled by tsc to

import { foo } from './bar.js';
function baz() { foo(); return 'hello' }

Which is an ES6 spec compliant module that will run on Node.js 12 or greater without further transpilation.

To see how tsc resolves a .js file we can use the --traceResolution option. For example, an excerpt of the output of yarn tsc --build --force packages/proto-parser --traceResolution run on the root of gcangussu/grpc-frame@943f62c is:

======== Resolving module './field-types-map.js' from '/grpcjs/packages/proto-parser/src/proto-parser.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module as file / folder, candidate module location '/grpcjs/packages/proto-parser/src/field-types-map.js', target file type 'TypeScript'.
File '/grpcjs/packages/proto-parser/src/field-types-map.js.ts' does not exist.
File '/grpcjs/packages/proto-parser/src/field-types-map.js.tsx' does not exist.
File '/grpcjs/packages/proto-parser/src/field-types-map.js.d.ts' does not exist.
File name '/grpcjs/packages/proto-parser/src/field-types-map.js' has a '.js' extension - stripping it.
File '/grpcjs/packages/proto-parser/src/field-types-map.ts' exist - use it as a name resolution result.
======== Module name './field-types-map.js' was successfully resolved to '/grpcjs/packages/proto-parser/src/field-types-map.ts'. ========

So, in short, the imported ./field-types-map.js resolves to ./field-types-map.ts.

By the name of this package, I would expect the behavior to mimic tsc's behavior shown above.

TypeError when importing from `'typescript'` in file

Whenever I have imports from 'typescript' module, I get type error: TypeError: Cannot read property 'type' of null. I'm not sure if it is caused by this package or is coming from somewhere else. However, when I comment out the line 'import/resolver': { typescript: { alwaysTryTypes: true } }, in .eslintrc.js file, then the file gets properly linted.

I created a small reproduction here: https://github.com/qlonik/eslint-import-resolver-typescript-repro

`import/no-duplicates` warn for duplicates imports from `.d.ts` file

I'm using date-fns and importing several helpers from the library:

import format from "date-fns/format";
import parseISO from "date-fns/parseISO";
import getUnixTime from "date-fns/getUnixTime";

With the rule import/no-duplicates enabled, I have this error:

'~/node_modules/date-fns/typings.d.ts' imported multiple times

I'm using the library properly and don't have duplicates so I guess it's a bug in the resolver no?

Plugin fails if no baseUrl is supplied

originally reported by @jhnns
#2 (comment)


After upgrading to 1.1.0 I get these errors in every file:

Resolve error: Unable to find tsconfig in /my/project/path: Missing baseUrl in compilerOptions import/no-unresolved
When I set...

"baseUrl": ".",
this plugin works fine. The problem is, however, that VSCode now generates paths on auto import that webpack and Node.js are not able to resolve:

// Instead of
import something from "../../shared/something";
// I get
import something from "src/shared/something";
I'm not sure if VSCode auto import is doing the right thing here, but I also think that baseUrl doesn't have to be set if I'm not using the paths option.

Path resolution works only with empty settings object

// .eslintrc.cjs

module.exports = {
    extends: [
        "eslint:recommended",
        "plugin:import/recommended",
        "plugin:import/typescript",
        "plugin:@typescript-eslint/recommended",
        "plugin:@typescript-eslint/recommended-requiring-type-checking",
    ],
    parserOptions: {
        ecmaVersion: 2018,
        extraFileExtensions: [".svelte"],
        project: ["./tsconfig.json"],
    },
    plugins: ["svelte3", "@typescript-eslint"], // same issue when import is explicitly included
    overrides: [
        {
            files: ["*.svelte"],
            processor: "svelte3/svelte3",
        },
    ],
    root: true,
    },
    settings: {
        // "import/resolver": {
        //     typescript: {},
        // },
        "svelte3/typescript": require("typescript"),
    },
}

This causes import resolution failures unless the import/resolver section is uncommented. It's a bit surprising that an empty config block modifies plugin behavior. It would be great if this worked without needing a blank config, otherwise perhaps the docs could be more explicit?

Add support for tsconfig paths

If you use the paths compiler option in your tsconfig.json, it would be nice if this resolver used your config to resolve it for you.

Tests don't pass

  1. Clone the repository.
    • On Windows, you'll need to set your Git configuration to have core.autocrlf=false. I have a fix for this in my fork.
  2. Install packages: yarn (Tested using Yarn 1.22.4)
  3. Run tests: yarn test

Expected behavior: ESLint reports 0 errors and 0 warnings.

Actual behavior: ESLint reports 26 errors. 22 import/no-unresolved and 4 import/extensions. Full output. Tested in two environments: Windows 10 w/ Node 10 and Ubuntu with w/ Node 13.

Version 1.1.x causes "Unable to resolve path to module" errors

When I allow npm to upgrade this package beyond 1.0.2 I get the following error output:

myfile.test.js
1:1 error Resolve error: Unexpected token ) import/no-unresolved
1:1 error Resolve error: Unexpected token ) import/no-extraneous-dependencies
4:34 error Unable to resolve path to module './myfile' import/no-unresolved

where myfile is a typescript module and myfile.test is a javascript unit test file.

This is what my .eslintrc.json looks like

{
    "parser": "babel-eslint",
    "env": {
        "jasmine": true,
        "es6": true,
        "browser": true,
        "node": true,
        "mocha": true
    },
    "settings": {
        "import/resolver": {
          "node": true,
          "eslint-import-resolver-typescript": true
        }
      },
    "plugins": ["jasmine", "react", "chai-friendly"],
    "extends": ["airbnb", "plugin:react/recommended"]
}

Let me know if you need more info. We don't use webpack as this is a node app that serves static HTML via React components

Custom `packageFilter` (and possibly `extensions`)

Hi,

I'm not sure this fits with your goals, particularly if you are aimed only at use with eslint-plugin-import, but your project appears to be a good fit for my project es-file-traverse. My project builds a list of file names that are found when traversing an entry file or files--whether through CJS require or ESM import, and whether through Node's algorithm or, through your project's help, through TypeScript's traversal algorithm.

The project's main use case is to list files to feed to eslint (so one can, for example, lint only those dependency files actually in use in one's project, e.g., for catching bad practices or vulnerabilities in one's dependencies). However, in linting TypeScript for such concerns, it is of less interest to follow a chain of TypeScript imports into 3rd party TypeScript declaration files than to follow say the TS source normally, but to prefer a JavaScript file over a declaration file.

So, I think it may be nice to be able to have a custom packageFilter and maybe a custom extensions, such that, for example, the module field could be given precedence over types and typings when .d.ts is the extension (or at least supply the extensions to the proposed custom packageFilter option callback). (It seems per microsoft/TypeScript#21423 that there are at least some projects using source in the wild to point to a main TS source file, so this might be preferable to even JS as it should in theory keep us in the TS source chain if a package bundles its source--more reliably than looking into tsconfig.json with its multiple entries could do.)

(Please note that I'm pretty new to TS though, so am hopefully not too far off in some of my ideas.)

If you'd be open to such an option, I can see about preparing a PR.

Thanks!

yarn-deduplicate

There's a postinstall hook for using yarn-deduplicate; this is visible when installing the package:

> [email protected] postinstall /app/node_modules/eslint-import-resolver-typescript
> yarn-deduplicate || exit 0

sh: yarn-deduplicate: not found

I assume this is just meant to be part of the build process here?

import/no-unresolved when trying to import types from @types/*

I'm trying to use eslint with @typescript-eslint/parser and eslint-plugin-import but no matter what I do, I get an error:

Unable to resolve path to module 'express-serve-static-core'  import/no-unresolved

whenever I try to import types from @types packages.

Looks like the sourceType: 'module' parserOption is causing this error but when I remove it I get another error:

Parsing error: ImportDeclaration should appear when the mode is ES6 and in the module context

I created a minimal example to reproduce this error. Probably it's just a setting that's wrong but I have tried different settings, plugins, parserOptions and what not and I just don't get it working:
https://github.com/manuelbieh/eslint-typescript-import-bug

So I'm not sure if the problem is on my side or if it is a bug in this package.

[RFC] Rename directory option to tsconfigPath or project

Coming from dividab/tsconfig-paths#91, tsconfigPaths.loadConfig(path) accepts a file path too not only a directory.

I think the directory option should be renamed to something more descriptive. I have 2 alternatives in mind:

  • tsconfigPath
  • project - will keep things consistent with @typescript-eslint/parser (parserOptions.project) - but it's in no way as descriptive as tsconfigPath

This will be a breaking change!

Won't work with custom modules

In my project I have some custom modules(a module @env for example, to use the react-native-dotenv package).
In VS Code the typescript recognize my module, and provide types and code completion, but when i try to import from this module, i'm still having import/no-unresolved being reported by ESLint.

I added this to my eslintrc:

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

Typescript Paths still unresolved for sub-folders config

Hello,

I'm trying to use React, Eslint, Typescript, Airbnb Config.
I want to use typescript paths, here @components.
The problem is that it works at the root of the project, but not using sub-folders.
The examples uses the structure of a monorepo using packages folder.

Packages are :

    "@typescript-eslint/eslint-plugin": "^2.7.0",
    "@typescript-eslint/parser": "^2.7.0",
    "eslint": "^6.6.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-import-resolver-typescript": "^2.0.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.16.0"

Here is a reproduction : https://github.com/n44ps/eslint-import-resolver-typescript-repro/

Thank you for your help !

n44ps

errors when importing default class from js file in tsx file

  4:24  error  Parse errors in imported module '../ScrollDown': '>' expected. (58:11)  import/no-named-as-default
  4:24  error  Parse errors in imported module '../ScrollDown': '>' expected. (58:11)  import/no-named-as-default-member

A.js

export default class A extends Component {}

B.tsx

import A from "./A";

versions:

  • eslint 5.9.0
  • eslint-import-resolver-typescript 1.1.1
  • eslint-plugin-typescript 0.13.0
  • typescript-eslint-parser 21.0.1
  • typescript 3.1.6

Also created an issue in eslint/typescript-eslint-parser#564 because I'm unclear about where this issue should be fixed.

Note that I tried to ignore import on tsx altogether, without success.

current .eslintrc
extends:
  - eslint-config-with-prettier
  - plugin:redux-saga/recommended
  - plugin:security/recommended

settings:
  react:
    version: 16.6.0
  import/resolver:
    babel-plugin-root-import: {}
    typescript: {} # use <root>/tsconfig.json
  import/parsers:
    typescript-eslint-parser: [ .ts, .tsx ]
  import/ignore:
    - \.tsx$  # Incorrect parse errors


parser: babel-eslint

plugins:
  - immutable
  - import
  - material-ui
  - redux-saga
  - security
  - typescript

parserOptions:
  ecmaVersion: 2018
  sourceType: "module"
  allowImportExportEverywhere: false
  codeFrame: false
  ecmaFeatures:
    legacyDecorators: true
    jsx: true

globals:
  firebase: true
  requirejs: true
  window: true
  _: true
  expect: true
  jest: true
  # enzyme vars (check jestsetup.js)
  shallow: true
  render: true
  mount: true

env:
  amd: true # for require.js (request() and define())
  browser: true
  commonjs: true
  es6: true
  mocha: true

rules:
  class-methods-use-this: 1
  flowtype/no-types-missing-file-annotation: 0
  immutable/no-mutation: 2
  import/named: 1
  import/order: error
  import/no-extraneous-dependencies: 0
  import/no-unresolved: error
  jsx-a11y/anchor-is-valid:
  - error
  - components:
    - Link
    specialLink:
    - to
  no-restricted-syntax:
    - error
    - selector: 'ForInStatement'
      message: 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.'
    - selector: 'LabeledStatement'
      message: 'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.'
    - selector: 'WithStatement'
      message: '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.'
  no-else-return:
    - "error"
    - allowElseIf: true
  one-var:
    - error
    - var: "always"
  prefer-destructuring:
    - error
    - object: false
  react/jsx-filename-extension: 0
  react/forbid-foreign-prop-types: 1
  react/prop-types: [2, {skipUndeclared: 1}]
  strict: 0
  typescript/class-name-casing: "error"
  typescript/no-unused-vars: "error"
  typescript/type-annotation-spacing: "error"

overrides:
  - files: ["*.ts", "*.tsx"]
    parser: "typescript-eslint-parser"
    parserOptions:
      ecmaFeatures:
        legacyDecorators: true
        jsx: true
        useJSXTextNode: true
    rules:
      import/no-unresolved: "error"

Requires a peer of eslint@* but none is installed

Updating eslint gives the following warning:

npm WARN [email protected] requires a peer of eslint@* but none is installed. You must install peer dependencies yourself.

But eslint 7.1.0 is already installed.

{
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^3.0.0",
    "@typescript-eslint/parser": "^3.0.0",
    "acorn": "^7.2.0",
    "eslint": "^7.1.0",
    "eslint-import-resolver-typescript": "^2.0.0",
    "eslint-plugin-array-plural": "^1.2.0",
    "eslint-plugin-const-case": "^1.2.2",
    "eslint-plugin-dollar-sign": "^1.0.2",
    "eslint-plugin-eslint-comments": "^3.1.2",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-jest": "^23.13.1",
    "eslint-plugin-jest-formatting": "^1.2.0",
    "eslint-plugin-jquery": "^1.5.1",
    "eslint-plugin-no-useless-assign": "^1.0.3",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-optimize-regex": "^1.2.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-requirejs": "^4.0.0",
    "eslint-plugin-security": "^1.4.0",
    "eslint-plugin-unicorn": "^20.0.0",
    "typescript": "^3.9.3"
}

Cannot read property 'directory' of null when not passing a config object

Other import-resolver plugins (e.g. webpack) allow you to use the default configuration by writing

settings: {
    'import/resolver': 'webpack'
}

in .eslintrc.

If you try this syntax with eslint-import-resolver-typescript, you get

  1:1   error    Resolve error: TypeError: Cannot read property 'directory' of null
    at initMappers (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-import-resolver-typescript\lib\cjs.js:102:38)
    at Object.resolve (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-import-resolver-typescript\lib\cjs.js:34:5)
    at v2 (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-module-utils\resolve.js:117:23)
    at withResolver (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-module-utils\resolve.js:122:16)
    at fullResolve (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-module-utils\resolve.js:139:22)
    at relative (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-module-utils\resolve.js:84:10)
    at resolve (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-module-utils\resolve.js:220:12)
    at isExternalRootModule (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-plugin-import\lib\rules\extensions.js:133:82)
    at checkFileExtension (C:\Projects\CareServices\CDS2\Source\node_modules\eslint-plugin-import\lib\rules\extensions.js:153:11)
    at listeners.(anonymous function).forEach.listener (C:\Projects\CareServices\CDS2\Source\node_modules\eslint\lib\linter\safe-emitter.js:45:58)

The error is being thrown on line 142 of index.ts where we try to access options.directory without checking options for null.

Ideally, we would use the default config if options == null.

I will plan to submit a PR for this sometime in the next month. If someone else can get to it faster than that, go for it.

Can't resolve path alias when wildcard is empty

I have the following paths config in my tsconfig.json

{
  ...
  "baseUrl": ".",
  "paths": {
      "@jest-utils*": ["tests/jest/test-utils*", "tests/jest/test-utils/index"]
    }
}

and this in my .tsx file

import { someFunc } from '@jest-utils'; // someFunc exported from tests/jest/test-utils/index

I get an eslint error from the import/no-unresolved rule but the typescript compiler can resolve the file just fine.
I don't get an eslint error for this:

import { someOtherFunc } from '@jest-utils/some-dir';

So it seems like it can't resolve the path when the wildcard is empty.

eslint config:

{
  ...
  "settings": {
    "import/parser": {
      "@typescript-eslint/parser": [".ts", ".tsx"]
    },
    "import/resolver": {
      "typescript": {}
    }
  }
}

[import/no-unresolved] when using with typescript "baseUrl" and "paths" option

Repro

tree
<root>
├── src
│   ├── index.ts
│   └── foo.ts
├── tsconfig.json
├── .eslintrc.js
...
└── package.json
tsconfig.json

Other options are omiited for brevity.

{
  "compilerOptions": {
    "baseUrl": "./src"
    "paths": {
      "#/*": ["./*"]
    }
  }
}
.eslintrc.js

Other options are omiited for brevity.

module.exports = {
  parser: '@typescript-eslint/parser',
  root: true,
  env: {
    node: true,
    es6: true,
  },
  plugins: ['@typescript-eslint', ],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:import/typescript',
  ],
}
src/index.ts
import { foo } from '#/foo'

console.log(`index.ts uses ${foo}`)

Problem

Expected Result

It should respect baseUrl and paths option on tsconfig.json

Actual Result

error  Unable to resolve path to module '#/foo'  import/no-unresolved

Additional Info

https://github.com/jjangga0214/ts-boilerplate/commit/af74c178a3c5ee84f78c520ba3c09ad73a9fc130/checks is the actual result with an error message. (Expand it by clicking "Lint" on github action checks)

Versions

package version
@typescript-eslint/eslint-plugin 2.2.0
@typescript-eslint/parser 2.2.0
eslint-plugin-import 2.18.2
TypeScript 3.6.3
ESLint 5.3.0
node 12.6.0
npm 6.10.2
yarn 1.17.3

Broken with Jest

🏳️ Waving a white flag for help here

I have a fully passing eslint test suite/configuration. yarn run eslint '**/*.ts*' works handsomely.

Upon tooling the project to leverage a runner (jest-runner-eslint), the suite blows up. Hundreds of failures are logged:

Resolve error: webpack with invalid interface loaded as resolver

Errors like this, I recall, were solved after I added eslint-import-resolver-typescript to my project. This leads me to believe that something is busted in the way Jest loads .eslintrc.js or uses this module.

Has anyone else experienced this issue?

Version 2 release missing on GitHub

Hey, thank you for all the work on this wonderful plugin.

I saw that after #29 was resolved, version 2 was published to npm 🎉

I couldn't find the release on GitHub which lists version 1.1.1 as the latest release and could also not find a changelog file. This makes me uncomfortable bumping to new major version as I'm running a very complex unejected CRA setup which I really don't want to break again. 😁

Could you provide some information on the breaking change(s)?

Resolver fails for relative paths

I have the following tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "lib": ["esnext"],
    "module": "commonjs",
    "noEmit": true,
    "noImplicitAny": true,
    "paths": {
      "axios-test-instance": ["index.ts"]
    },
    "strict": true,
    "target": "esnext"
  }
}

TypeScript 4.1 supports using relative paths without the baseUrl option. This means the following works with TypeScript now:

{
  "compilerOptions": {
    "lib": ["esnext"],
    "module": "commonjs",
    "noEmit": true,
    "noImplicitAny": true,
    "paths": {
      "axios-test-instance": ["./index.ts"]
    },
    "strict": true,
    "target": "esnext"
  }
}

However, this makes eslint-import-resolver-typescript unable to resolve the mapped paths.

@typescript-eslint treats imports as any in second package

I have a project in the root directory, and a packages folder with some git submodules inside. I'm liniting using the same .eslintrc.js across all packages and the root with one config file that resides inside packages/shared/.eslintrc.js. I share this configuration across front-end and back-end.

Everything works great on the root directory, but inside packages/some-package, I am getting errors. I managed to fix it not recognizing the paths like import SomeClass from 'path-import/subfolder/SomeClass', but when I instantiate or use that class I am getting some weird errors.

For example:

//packages/some-package/src/index.ts
import SomeClass from 'path-import/subfolder/SomeClass';
const instance = new SomeClass();

Gives me: ESLint: Unsafe construction of an any type value.(@typescript-eslint/no-unsafe-call).

That happens across the whole packages/some-package, that when I import something from another file @typescript-eslint treats that type as an any type.

For example, when I have a class with a property:

//packages/some-package/src/path-import/subfolder/SomeClass';
import AnotherClass from 'path-import/another-subfolder/AnotherClass';
export default class SomeClass {
  public someProperty: AnotherClass;
  public someMethod() {
    return this.someProperty.xd;
  }
}

I will get ESLint: Unsafe member access .xd on an any value.(@typescript-eslint/no-unsafe-member-access).

.eslintrc.js
...
	'env': {
		'browser': true,
		'node': true
	},
	'extends': [
		'plugin:@typescript-eslint/recommended',
		'plugin:@typescript-eslint/recommended-requiring-type-checking'
	],
	'parser': '@typescript-eslint/parser',
	parserOptions: {
		// tsconfigRootDir: __dirname,
		project: 'packages/shared/tsconfig.eslint.json',
		'sourceType': 'module'
	},
	'plugins': [
		'@typescript-eslint',
		'import'
	],
	'settings': {
		'import/parsers': {
			'@typescript-eslint/parser': ['.ts', '.tsx']
		},
		'import/resolver': {
			'typescript': {
				'alwaysTryTypes': true // always try to resolve types under `<root>@types` directory even it doesn't contain any source code, like `@types/unist`
			}
		}
	},
...
.eslintrc.frontend.js
module.exports = {
	'extends': [
		'plugin:react/recommended',
		'.eslintrc.js'
	],
	parserOptions: {
		ecmaFeatures: {
			jsx: true
		}
	},
	settings: {
		react: {
			version: 'detect'
		},
		'import/parsers': {
			'@typescript-eslint/parser': ['.ts', '.tsx']
		},
		'import/resolver': {
			// use <root>/tsconfig.json
			'typescript': {
				'directory': [
					'packages/*/tsconfig.json',
					__dirname
				],
				'alwaysTryTypes': true // always try to resolve types under `<root>@types` directory even it doesn't contain any source code, like `@types/unist`
			}
		}
	},
	'rules': {
		'react/no-unescaped-entities': 0,
		'react/display-name': 0,
	}
};
package.json - frontend Then in `package.json` in the frontend:
...
  "eslintConfig": {
    "extends": "./packages/shared/.eslintrc.react.js"
  },
...
versions
//package.json
...
//"devDependencies"
    "@typescript-eslint/eslint-plugin": "^3.6.1",
    "@typescript-eslint/parser": "^3.6.1",
    "eslint": "^7.4.0",
    "eslint-import-resolver-typescript": "^2.0.0",
    "eslint-plugin-import": "^2.22.0",
...

v2.0.0 prefers '.d.ts' files to '.js' files when both exist.

In v2.0.0, it seems that the change from:

  const extensions = Object.keys(require.extensions).concat(
    '.ts',
    '.tsx',
    '.d.ts',
  );

to:

const extensions = ['.ts', '.tsx', '.d.ts'].concat(
  // eslint-disable-next-line node/no-deprecated-api
  Object.keys(require.extensions),
  '.jsx',
)

...means that if a node module is imported and contains both .js and .d.ts files, the .d.ts file is now resolved instead of the .js one. This results in import/default errors, e.g.:

import React from 'react';
error: No default export found in module (import/default)

Maybe I'm missing something obvious?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Cannot resolve estree types

Steps to reproduce

This repo is setup with pnpm, which helps putting multiple packages in a single repo. You can install with npm install -g pnpm if you don't have it already.

git clone [email protected]:benmccann/plugins.git
cd plugins
git checkout pluginutils-eslint
pnpm install
cd packages/pluginutils
pnpm lint

Actual results

packages/pluginutils/src/extractAssignedNames.ts
7:8 error Unable to resolve path to module 'estree' import/no-unresolved

Expected results

I'd expect this to pass linting since the root directory contains an node_modules/@types/estree/index.d.ts file with the types.

Maybe it doesn't work when there's only types and not the actual .js code? Or maybe it doesn't know how to look in the node_modules of parent directories? Or maybe I just messed something up in the setup?

2.0.0 Doesn't work with lodash

It always throws errors like this(no errors in previous version):

9:10  error  throttle not found in 'lodash'  import/named

Node version: 12.11.1

Relevant dependencies:

{
    "@typescript-eslint/parser": "2.3.3",
    "@types/lodash": "4.14.142",
    "eslint": "6.5.1",
    "eslint-import-resolver-typescript": "2.0.0",
    "eslint-plugin-import": "2.18.2",
    "lodash": "4.17.15",
    "typescript": "3.6.3"
}

Unable to resolve path when import uses path relative to `baseUrl`

This is a difficult one to describe but here is a failing test: OliverJAsh@e26fed2

Essentially the issue occurs when we import using a path that is relative to the baseUrl, e.g. given:

tests/withPaths2/tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "root/",
    "paths": {
      "other/*": ["../other/*"]
    }
  },
  "files": ["root/foo.ts", "other/bar.ts"]
}

tests/withPaths2/root/foo.ts:

// import using tsconfig.json path mapping
import 'other/bar'

tests/withPaths2/other/bar.ts:

// import using tsconfig.json `baseUrl`
// This one fails ❌
import 'foo'

This fails with the following error:

/Users/oliverash/Development/eslint-import-resolver-typescript/tests/withPaths2/other/bar.ts
  2:8  error  Unable to resolve path to module 'foo'  import/no-unresolved

This is a valid import—TypeScript understands it so I think this resolver should also understand it.

npm package maintenance issue

Hi @alexgorbatchev @bradzacher
Although I'm one of the GitHub collaborator of this project, but I'm not a publisher of its npm package, so even I can merge PRs, but I can't help to release a patch version into npm.

Would you like to help with this situation?

types vs typings

as Typescriopt doc says

If you still can't find it, check if it bundles its own typings. This is usually provided in a "types" or "typings" field in the package.json, or just look for any ".d.ts" files in the package and manually include them with a /// <reference path="" />.

but in fact I have problem with typings

it works with config (actually only "ts" section is enough, alwaysTryTypes could be any)

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

and does not work (is highlighted) with

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

you can try these configs on this code (package)

import React from "react";
import {FieldRenderProps} from "react-final-form";

This plugin breaks disabling import rules

When I install this plugin along eslint-plugin-import I can not use eslint-disable import/<whatever>

For example, I used
/* eslint-disable import/no-extraneous-dependencies */

Eslint reports me:
error 'import/no-extraneous-dependencies' rule is disabled but never reported eslint-comments/no-unused-disable

N.B: I extends the plugin and also list some rules:

extends: [
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:import/typescript',
],
rules: {
  'import/no-extraneous-dependencies': ['error', { devDependencies: true }],
}

If I remove the eslint-disable then import correctly report an extraneous import, that means the rules is reported but someway eslint does recognise it 🤷🏻‍♂️

Importing modules from d.ts

Hi,

I have a case within a project that I tried to reduce to a minimal repro, see here: https://github.com/jeffrson/import_unresolved_dts

eslint with eslint-import-resolver-typescript apparently fails to recognize a module from d.ts, whether or not it is located in / or /@types.

startup.ts looks like this

import { ITest } from 'module1'

const i: ITest = { test1: '1' }
console.log(i)

and there's a file called my_modules.d.ts (name shouldn't matter):

declare module 'module1' {
    export interface ITest {
        test1: string
    }
}

which, when linting, shows the import/no-unresolved error.

import/default error in monorepo project in Typescript

I'm trying to use eslint-import-resolver-typescript in a monorepo project but I have an unresolved ESlint error despite the right config (I believe).

This is the architecture of the project:

api/
  src/
    index.ts
  package.json
  tsconfig.json
app/
  package.json
  tsconfig.json
.eslintrc
tsconfig.json
package.json

And this is the configuration of each config files:

tsconfig.json

{
  "compilerOptions": {
    "allowJs": false,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "lib": ["dom", "es2020"],
    "module": "es2020",
    "moduleResolution": "node",
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
    "target": "es2020",
    "typeRoots": ["typings", "node_modules/@types"]
  },
  "references": [
    {
      "path": "./api"
    },
    {
      "path": "./app"
    }
  ]
}

api/tsconfig.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./src",
    "composite": true,
    "module": "commonjs",
    "outDir": "dist",
  },
  "include": ["./src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

app/tsconfig.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "baseUrl": "./",
    "composite": false
  },
  "exclude": ["node_modules"],
  "include": ["./**/*.ts", "./**/*.tsx"]
}

.eslintrc

{
  "root": true,
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 2020,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    },
    "project": ["./api/tsconfig.json", "./app/tsconfig.json"]
  },
  "plugins": ["@typescript-eslint", "import"],
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
    "plugin:prettier/recommended"
  ],
  "env": {
    "browser": true,
    "node": true
  },
  "settings": {
    "react": {
      "version": "detect"
    },
    "import/parsers": {
      "@typescript-eslint/parser": [".ts", ".tsx"]
    },
    "import/resolver": {
      "typescript": {
        "directory": ["./api/tsconfig.json", "./app/tsconfig.json"]
      }
    }
  }
}

In my api/src/index.ts file when I import express with default import syntax import express from "express" I have this error :

No default export found in imported module "express". eslint(import/default)

I have @types/express installed in devDependencies. Could you check if I missed something in my ESlint config or if it's a bug with composite tsconfig that doesn't understand allowSyntheticDefaultImports option ?

Resolving dynamically imported types

Steps to reproduce

This repo is setup with pnpm, which helps putting multiple packages in a single repo. You can install with npm install -g pnpm if you don't have it already.

git clone [email protected]:benmccann/plugins.git
cd plugins
git checkout pluginutils-linting-dynamic-type-import
pnpm install
cd packages/pluginutils
pnpm lint

Actual results

packages/pluginutils/src/extractAssignedNames.ts
8:57 error 'ArrayPattern' is not defined no-undef
14:62 error 'AssignmentPattern' is not defined no-undef
18:55 error 'Identifier' is not defined no-undef
24:58 error 'ObjectPattern' is not defined no-undef
35:56 error 'RestElement' is not defined no-undef

This is being caused by referencing types from dynamic imports as seen here: https://github.com/benmccann/plugins/blob/ac78a7b81b822f63f6a004a9c67b594e0d3689e0/packages/pluginutils/src/extractAssignedNames.ts#L8

Expected results

I'd expect this to pass linting since the root directory contains an node_modules/@types/estree/index.d.ts file with the types. It does work if I do import type { ArrayPattern} from 'estree' at the top of the file. However, the package maintainer does not want to use that style and would prefer we keep the dynamic imports.

Unable to resolve path to module eslint(import/no-unresolved) when using "paths" in tsconfig.json

I have a simple project in a ClientApp/ folder.
In it, I have tsconfig.json, .eslintrc, package.json and a /src/components folder containing my ts/tsx files.
I want to use the "paths" config in tsconfig so that I can simplify/shorten my imports.

However, I always get the same "import/no-unresolved" error message: Unable to resolve path to module 'common'.eslint(import/no-unresolved)

Any idea on whether this is a bug or I'm doing something wrong?

Sample Project:

sample-unresolved.zip

Sample Code:

tsconfig.json:

{
	"compilerOptions": {
	  "target": "es5",
	  "lib": [
		"dom",
		"dom.iterable",
		"esnext"
	  ],
	  "allowJs": true,
	  "skipLibCheck": true,
	  "esModuleInterop": true,
	  "allowSyntheticDefaultImports": true,
	  "strict": true,
	  "forceConsistentCasingInFileNames": true,
	  "noFallthroughCasesInSwitch": true,
	  "module": "esnext",
	  "moduleResolution": "node",
	  "resolveJsonModule": true,
	  "isolatedModules": true,
	  "noEmit": true,
	  "jsx": "react-jsx",
	  "paths": {
		  "common": ["./src/components/common"],
		  "common/*": ["./src/components/common/*"]
	  }
	},
	"include": [
	  "src/**/*"
	]
  }

.eslintrc

{
	"root": true,
	"extends": [
	  "eslint:recommended",
	  "plugin:@typescript-eslint/eslint-recommended",
	  "plugin:@typescript-eslint/recommended",
	  "plugin:import/errors",
	  "plugin:import/typescript"
	],
	"parserOptions": {
	  "project": "tsconfig.json"
	},
	"settings": {
	  "import/resolver": {
		"typescript": {
		     "project": "tsconfig.json"
		}
	  }
	}
  }

packages.json

...
"devDependencies": {
    // ... simplified
    "@typescript-eslint/eslint-plugin": "4.20.0",
    "@typescript-eslint/parser": "4.20.0",
    "eslint": "7.23.0",
    "eslint-config-prettier": "8.1.0",
    "eslint-import-resolver-typescript": "2.4.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jest": "24.3.2",
    "eslint-plugin-prettier": "3.3.1",
    "eslint-plugin-react": "7.23.1",
    "eslint-plugin-react-hooks": "4.2.0"
  },

App.tsx (this is the problematic import)

**import { MyComponent } from 'common'**
// ...

In my VSCode settings file for that project:

        // ...
	"eslint.validate": [
		"javascript",
		"javascriptreact",
		"typescript",
		"typescriptreact"
	],
	"eslint.workingDirectories": [
		{
			"directory": "ClientApp",
			"changeProcessCWD": true,
			"mode": "auto"
		}
	],
	"editor.codeActionsOnSave": { "source.fixAll.eslint": true },

resolver fails when importing a node_module ending in `.js`

Originally reported by @vkrol via pr #5


If the "import/extensions" rule is activated then the following import statement causes the error:

import "popper.js";
causes the following error

Resolve error: Cannot find module 'popper' from 'D:\Projects\eslint-import-resolver-typescript\tests' import/extensions

[FEAT] Multiple tsconfig.json support

I am currently working on a yarn workspaces monorepo with one eslint config file at the root.
@typescript-eslint/parser supports multiple eslint configs trough parserOptions.projects

I am not sure if this can be automated (i.e. the plugin reads parserOptions.projects)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.