microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.08k stars 12.37k forks source link

Auto import option to make imports relative only within current directory #45015

Open JordanLongstaff opened 3 years ago

JordanLongstaff commented 3 years ago

Suggestion

🔍 Search Terms

import relative

✅ Viability Checklist

My suggestion meets these guidelines:

⭐ Suggestion

An option added to the importModuleSpecifier preference to make imports absolute if and only if their relative path would begin with ../.

📃 Motivating Example

At my workplace, our least favourite relative imports are the ones that venture out of the current directory (i.e. they begin with any number of ../). But there are times where we want relative imports within the current directory (i.e. beginning with ./). I don't see any existing options that support this exact style of import, including project-relative.

In general, the motivation for not using relative imports beginning with ../ is that it makes moving code files around more difficult.

💻 Use Cases

shortest and relative are obviously not correct since they have no qualms about this issue. non-relative is my current workaround, which only adds absolute imports. project-relative I tried, but based on what I discovered and my understanding of the description in the tooltip, my guess is that it only adds absolute imports for files that are located outside of the workspace folder.

akomm commented 2 years ago

This is a quite underrated proposal. Could prevent issues like this: https://github.com/remix-run/remix/issues/1580

Most problems I try to avoid come from "../" imports. While in the same directory, "./" imports are fine.

I think this behavior even correlates with the way how namespace resolution in languages usually work. You either give an absolute namespace, or you give a relative one, narrowing down but not up.

Name proposal for the option: non-relative-parents (this totally makes sense I know)