eslint-import-resolver-typescript

repository·master·Indexed 21 days ago

https://github.com/import-js/eslint-import-resolver-typescript

A resolver for ESLint import plugins that adds TypeScript support to eslint-plugin-import and eslint-plugin-import-x. It enables ESLint to understand TypeScript file extensions, @types definitions, and tsconfig.json path mappings. It includes support for Bun built-in module resolution and provides a createTypeScriptImportResolver factory function for integration with ESLint flat config.

Tokens
2.2K
Snippets
8
Records
11
Agent score
74%

What's inside eslint-import-resolver-typescript

  1. Configure eslint-import-resolver-typescript in .eslintrc

    master

    Add the resolver to your .eslintrc configuration under settings.import/resolver.typescript. This allows ESLint to resolve TypeScript files and respect tsconfig.json paths.

    {
      "plugins": ["import"],
      "rules": {
        "import/no-unresolved": "error"
      },
      "settings": {
        "import/parsers": {
          "@typescript-eslint/parser": [".ts", ".tsx"]
        },
        "import/resolver": {
          "typescript": {
            "alwaysTryTypes": true,
            "bun": true,
            "project": "path/to/folder"
          }
        }
      }
    }
  2. Install eslint-import-resolver-typescript

    master

    Install the resolver along with your preferred ESLint import plugin.

    For eslint-plugin-import-x (recommended for speed):

    # npm
    npm i -D eslint-plugin-import-x eslint-import-resolver-typescript
    
    # pnpm
    pnpm i -D eslint-plugin-import-x eslint-import-resolver-typescript
    
    # yarn
    yarn add -D eslint-plugin-import-x eslint-import-resolver-typescript
    
    # bun
    bun add -d eslint-plugin-import-x eslint-import-resolver-typescript

    For eslint-plugin-import:

    # npm
    npm i -D eslint-plugin-import eslint-import-resolver-typescript
    
    # pnpm
    pnpm i -D eslint-plugin-import eslint-import-resolver-typescript
    
    # yarn
    yarn add -D eslint-plugin-import eslint-import-resolver-typescript
    
    # bun
    bun add -d eslint-plugin-import eslint-import-resolver-typescript
    npm i -D eslint-plugin-import-x eslint-import-resolver-typescript
  3. Configure eslint-import-resolver-typescript in eslint.config.js (Flat Config)

    master

    If you are using eslint-plugin-import-x@>=4.5.0, you can use createTypeScriptImportResolver to reference the resolver directly in your ESLint flat config.

    For older versions of eslint-plugin-import-x or when using eslint-plugin-import, use the import/resolver key in the settings object instead.

    // For eslint-plugin-import-x@>=4.5.0
    import { createTypeScriptImportResolver } from 'eslint-import-resolver-typescript'
    
    export default [
      {
        settings: {
          'import-x/resolver-next': [
            createTypeScriptImportResolver({
              alwaysTryTypes: true,
              bun: true,
              project: 'path/to/folder',
            }),
          ],
        },
      },
    ]
  4. Enable Bun built-in module resolution

    master

    Bun provides built-in modules like bun:test that are not resolved by default. To enable resolution for these modules, use one of the following methods:

    1. Set the bun: true option in your resolver configuration.
    2. Run ESLint using the Bun runtime: bun --bun eslint.
    3. Configure run.bun in your bunfig.toml to automatically alias node to bun.
    // In your config
    {
      "typescript": {
        "bun": true
      }
    }
  5. Configure the `project` option for tsconfig resolution

    master

    The project option tells the resolver which tsconfig.json or jsconfig.json files to use for module resolution. This is essential for supporting paths mapping.

    Supported formats:

    • A single path to a folder: 'path/to/folder'
    • A glob pattern: 'packages/*/{ts,js}config.json'
    • An array of specific paths: ['packages/module-a/tsconfig.json', 'packages/module-b/jsconfig.json']
    • An array of glob patterns: ['packages/*/tsconfig.json', 'other-packages/*/jsconfig.json']
    project: 'path/to/folder'
    // or
    project: ['packages/module-a/tsconfig.json', 'packages/module-b/jsconfig.json']
  6. How the resolve function works

    master

    The core resolve function performs the following steps to find a module:

    1. Builtin Check: It first checks if the source is a Node.js or Bun builtin module. If so, it returns found: true with no path.
    2. Querystring Removal: It strips query strings from the source string.
    3. Project Matching: If options.project is provided, it identifies the correct tsconfig.json that matches the file being linted. It uses sortProjectsByAffinity to prioritize the most relevant configuration.
    4. Resolver Execution: It uses an underlying ResolverFactory (via unrs-resolver) to perform the actual file system lookup.
    5. Type Definition Fallback: If a module is not found, and alwaysTryTypes is not false, it attempts to resolve the module via the @types/ scope (e.g., resolving lodash to @types/lodash).

    Returns a ResolvedResult object:

    • found: boolean indicating if the module was located.
    • path: string | null containing the absolute path to the resolved file if found is true.
  7. Configure TypeScriptResolverOptions

    master

    The resolver is configured via TypeScriptResolverOptions. Key behaviors include:

    • project: An array of paths to tsconfig.json files. If provided, the resolver will attempt to match the current file to the most appropriate TypeScript project.
    • alwaysTryTypes: A boolean (defaults to true) that determines whether the resolver should attempt to find @types/ packages for non-absolute, non-relative imports that fail initial resolution.
    • tsconfig: An object allowing fine-grained control over TypeScript configuration, such as setting references: 'auto' or specifying a configFile.
    • bun: A boolean to explicitly enable Bun-specific builtin module detection.

    Note: The resolver uses normalizeOptions internally to ensure these settings are applied correctly relative to the current working directory.

  8. Configure TypeScriptResolverOptions for eslint-import-resolver-typescript

    master

    When configuring eslint-import-resolver-typescript in your ESLint settings, you can provide a TypeScriptResolverOptions object. This object controls how the resolver locates TypeScript files and handles type definitions.

    Key options include:

    • project: A string or an array of strings specifying the path to your tsconfig.json files.
    • alwaysTryTypes: A boolean that determines whether the resolver should always attempt to resolve @types packages. Defaults to true.
    • bun: A boolean indicating whether bun core modules should be accounted for during resolution.
    • noWarnOnMultipleProjects: A boolean to suppress warnings when multiple TypeScript projects are detected.
    {
      "settings": {
        "import/resolver": {
          "typescript": {
            "project": ["tsconfig.json", "tsconfig.node.json"],
            "alwaysTryTypes": true,
            "bun": false,
            "noWarnOnMultipleProjects": true
          }
        }
      }
    }
  9. Reference: Resolver configuration options

    master

    The resolver accepts options passed through to unrs-resolver.

    Key options include:

    • alwaysTryTypes: (Boolean) Always try to resolve types under <root>@types directory even if it doesn't contain any source code.
    • bun: (Boolean) Resolve Bun modules.
    • project: (String | String[] | Glob) Path(s) to tsconfig.json or jsconfig.json.
    • conditionNames: (Array) Custom export conditions to check.
    • extensions: (Array) File extensions to attempt resolving.
    • extensionAlias: (Object) Mapping of extensions to their aliases.
    • mainFields: (Array) Fields in package.json to check for module entry points.
  10. Use createTypeScriptImportResolver to integrate with ESLint

    master

    To use this resolver with ESLint (specifically with eslint-plugin-import or eslint-plugin-import-x), you should use the createTypeScriptImportResolver factory function. This function returns an object compatible with the ESLint resolver interface, including the interfaceVersion, name, and a resolve method.

    When called by ESLint, the resolve method automatically handles context (like cwd) and uses the provided TypeScriptResolverOptions to locate TypeScript modules.

    import { createTypeScriptImportResolver } from 'eslint-import-resolver-typescript';
    
    // This is what you would typically configure in your ESLint settings
    const resolver = createTypeScriptImportResolver({
      project: ['tsconfig.json'],
      alwaysTryTypes: true
    });