microsoft / TypeScript

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

Auto-imports from code actions and completions don't match order that "Organize imports" outputs #60492

Open MariaSolOs opened 1 day ago

MariaSolOs commented 1 day ago

🔎 Search Terms

"auto-import", "order", "import", "organize imports"

🕗 Version & Regression Information

⏯ Playground Link

No response

💻 Code

In a simple npm package with just TypeScript 5.6.3 installed, create a TypeScript file with the following content:

import { foo } from "@foo";
import { bar } from "@bar";
import { a } from "workspace-a";
import { b } from "workspace-b";

console.log(foo + bar + a + b)

Now at the end of the file type is and select the completion isAccessor that brings the import from TypeScript.

🙁 Actual behavior

The import from the completion is added below import { b } from "workspace-b";, but notice how the import gets moved to the middle if one runs the "Organize imports" command in VS Code.

🙂 Expected behavior

For completions and code actions that add an import to use the same ordering logic that the "Organize imports" command uses. After all this seems to be advertised by https://github.com/microsoft/TypeScript/pull/52115 ("These rules will also apply to auto-imports and import fixes, which will use the user's collation preferences to determine if a list of import or export specifiers is already sorted before selecting an insertion point").

Additional information about the issue

No response

iisaduan commented 22 hours ago

@MariaSolOs When you run organizeImports, does the order of the first two imports (the one from @foo and @bar) also flip? Seems like this case should have autoimports adding onto the end because the original imports are unsorted.

MariaSolOs commented 21 hours ago

@MariaSolOs When you run organizeImports, does the order of the first two imports (the one from @foo and @bar) also flip? Seems like this case should have autoimports adding onto the end because the original imports are unsorted.

@iisaduan It does. And indeed, if I follow the repro steps above using this file:

import { bar } from "@bar";
import { foo } from "@foo";
import { a } from "workspace-a";
import { b } from "workspace-b";

console.log(foo + bar + a + b)

Then the bug doesn't happen.

HOWEVER it does happen with this file:

import { bar } from "@bar";
import { foo } from "@foo";
import { a } from "workspace-a";
import { b } from "workspace-b";
import { x } from "../file1";
import { y } from "./file2";

console.log(foo + bar + a + b + x + y);

Using the above content, organizeImports makes no changes. Now at the bottom of the file start typing is and select the completion for isAccessor. The import goes below the import of y, but then it's moved above a if one runs organizeImports.