Skip to content

Auto import improvement for directory. #46134

Open

Description

Suggestion

I have many components in my project, like:

components/
      button/
            button.tsx            // export class Button
            package.json       // { "main": "./button.tsx" }
     index.ts                      // export * from "./button"
pages/
    a.tsx

When auto importing Button in a.tsx.

Expected behavior

import {Button} from "./components/button";

Actual behavior

  1. import {Button} from "./components/button/button";
  2. import {Button} from "./components/";

When import button/index.ts, TS will omit index and use button automatically, but custom index file is not supported, through they can be loaded by specifying main/types field of package.json.

One workaround is to rename all components to index.tsx, but it is a bad practice for two reasons:

  1. When an error raised in one of the component, DevTools will only print index.tsx in source section.
  2. When I opened many components at same time, it is very hard to find the correct index.tsx.

In addition, TS do not support multiple * and RegExp in paths of tsconfig.json,
I cannot write paths like:

{
   "compilerOptions": {
      "path": {
         "./components/*": ["./components/*/*.ts"]
      }
   }
}

I have to add a 'package.json' to each component folder which only contains one line: {"main": "./<dirname>.tsx"}, which is too verbose.

components/index.ts re-exports all components in this directory. It is designed for users outside of this project.
I prefer direct exports over re-exports in components directory. (Mixed: #45015, #43777)

🔍 Search Terms

auto import shortest directory

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Auto-import feature improvement for best practise.

📃 Motivating Example

💻 Use Cases

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureDomain: Auto-importSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions