TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Auto-import priority rules

Open theoephraim opened this issue 3 years ago • 21 comments
trafficstars

Suggestion

It seems there are many folks struggling with the priority/ordering of VSCode's auto-import (intellisense) suggestions. There are a few different cases, but they seem to be all somewhat related to the general theme of how these suggestions are prioritized.

  • My specific case is that when coding in Vue, the import of watch from fs is always prioritized over vue (/cc @cabal95)
  • Others have issues with code from external modules being prioritized over code defined within their repo
  • Others have issues related to preferring aliases defined in their tsconfig
  • Many edge cases around specific paths suggested when dealing with monorepos...

It would be fantastic if VSCode provided a way to override the priority but it seems that TypeScript's language server suggestions could use some tweaking regardless.

⭐ Suggestion

Seems like a fairly reasonable priority would be:

  • code found within the repo/module (preferring aliased paths if they exist, probably preferring "closer" imports over further away in the tree?)
  • code found in other repos/modules defined locally within a monorepo (again preferring aliases)
  • code found in explicit dependencies found in package.json
  • code found in node internals (ex: fs, path)

🔍 Search Terms

import priority prioritize prioritise auto-import vscode intellisense

🔗 Related Issues

open

  • https://github.com/microsoft/TypeScript/issues/31710
  • https://github.com/microsoft/TypeScript/issues/43352

closed

  • https://github.com/microsoft/TypeScript/issues/43849
  • https://github.com/microsoft/vscode/issues/29613
  • https://github.com/microsoft/TypeScript/issues/15024

theoephraim avatar Oct 12 '22 20:10 theoephraim

None of the things you've listed are first-class concepts in TS -- basically, when we're running, it's all just files and/or ambient module declarations. Formal definitions of what it means to "be defined locally in a monorepo" or "be a node internal" would be needed

RyanCavanaugh avatar Oct 12 '22 22:10 RyanCavanaugh

@RyanCavanaugh - thanks for replying!

Do you think there would be a willingness to add these concepts and get something implemented?

It seems this is the main file involved?

I'm thinking some of the edge cases around monorepos might get pretty nasty, but I would think sorting the explicit imports before node built-in modules may be straightforward.

theoephraim avatar Oct 13 '22 02:10 theoephraim

Adding another similar issue from VS Code repo that was also closed: https://github.com/Microsoft/vscode/issues/42104. It seems like on of the issues tracked in this ticket was resolved, but the main issue of import priority was not.

no-stack-dub-sack avatar Oct 14 '22 17:10 no-stack-dub-sack

Was going to open an issue about this... thankfully I found this one.

I would add that the way that autosuggest is matching/suggesting imports vs quick fix seems to be inconsistent.

e.g. I want to add the import line automatically: import { Assessment } from '@shared/models/Assessment';

@shared is an alias to an in-house shared types project in our monorepo.

Two types of problems seem to be apparent:

  • Quick fix prefers a library imported via node_modules, which is almost always non-preferred Screenshot 2023-04-06 at 4 04 02 pm

  • Suggestion dropdown doesn't even offer it as an option, even when scrolling all the way down (whether I use 'assessment' or 'Assessment' doesn't change the results) Screenshot 2023-04-06 at 4 04 21 pm

Tightening this all up will offer a huge productivity boost.

jpike88 avatar Apr 06 '23 09:04 jpike88

This is definitely annoying to our team as well - we have a lot of generic React components like <Input />, <Button />, etc. And each time the auto-import suggests alternatives found in external dependencies first, even though local code seems to be a fairly reasonable thing to prefer. Ideally, this would be something you can set in settings (e.g. "javascript.preferences.autoImportPriority": ["local", "alias", "./src/somemodule.js", "some_node_module"]). It seems like a minor problem but is often one of the most annoying things to deal with as these things tend to go unnoticed unless the component API is not the same, or someone notices that during code review.

rgembalik avatar Jun 29 '23 14:06 rgembalik

would be great if this could be further customizable to allow solving for collisions across external packages as well

a few anecdotal examples from our app

  1. useQuery is exported by both @chakra-ui/react (for media queries) and @apollo/client (to make graphql requests), for our app we never use useQuery from chakra and always want the one from @apollo/client, but for some reason the @chakra-ui/react always shows up first
  2. gql is exported by both @apollo/client and graphql-request. 99% of the time we want the one from apollo client

cheapsteak avatar Aug 04 '23 21:08 cheapsteak

would really be great for us as well, we have many conflicting names of types which are imported first from the node_modules libraries rather than from our code (e.g. User, BaseEntity, etc)

MatthieuVegreville avatar Sep 12 '23 05:09 MatthieuVegreville

What about sorting suggestions by popularity?

When you already imported useQuery a bunch of times from react-query in your current project, it probably makes sense to suggest that over a useQuery exported from a module that you have never used.

There can also be other heuristics, but this feels like a good start.

jguddas avatar Sep 15 '23 10:09 jguddas

I thinks sane defaults would be in order:

  • internal project files
  • aliases in tsconfig
  • node_modules

Beyond that being able to specify overrides would make sense too though.

jpike88 avatar Sep 15 '23 12:09 jpike88

Related on Stack Overflow: VS Code TypeScript auto import suggestion priority

starball5 avatar Oct 20 '23 04:10 starball5

Second this, Suggesting to import ex. ../../components instead of a @/components alias can get annoying.

robiot avatar Dec 01 '23 15:12 robiot

Have a similar experience with angular, For EventEmitter the first suggestion is from the "stream" library, but the preferred option is @angular/core, this takes a few seconds each time to figure out that the wrong thing is imported.

NonerDude avatar Feb 18 '24 06:02 NonerDude

@robiot If you have the alias configured in your tsconfig.json, there is already a setting that should do what you want.

typescript.preferences.importModuleSpecifier: "non-relative"

Prefers a non-relative import based on the baseUrl or paths configured in your jsconfig. json / tsconfig. json.

Screenshot 2024-02-19 at 11 50 08 AM

Snippet from tsconfig.json:

{
  "compilerOptions": {
     ...
    "paths": {
      "@/*": ["./src/*"]
    }
}

Import suggestion:

Screenshot 2024-02-19 at 11 54 11 AM

michael-gillett avatar Feb 19 '24 16:02 michael-gillett

@robiot If you have the alias configured in your tsconfig.json, there is already a setting that should do what you want.

typescript.preferences.importModuleSpecifier: "non-relative"

Prefers a non-relative import based on the baseUrl or paths configured in your jsconfig. json / tsconfig. json.

Screenshot 2024-02-19 at 11 50 08 AM ### Snippet from tsconfig.json: ```json { "compilerOptions": { ... "paths": { "@/*": ["./src/*"] } } ```

Import suggestion:

Screenshot 2024-02-19 at 11 54 11 AM

Thats a good tip, but in my case I have a design system built on top of MUI and it keeps preferring @mui vs our design system (in a monorepo using turbo)... I actually sort of hacked it with snippets by creating a couple that start with "import" i.e. "import-design-system"

zrosenbauer avatar Feb 19 '24 20:02 zrosenbauer

You can change the auto-complete suggestions and code fix (quick fix) with a TypeScript Plugin. A TypeScript Plugin has to be a package (cannot be a local file), so I made one: https://github.com/tidalhq/ts-plugin-sort-import-suggestions

image

If you are interested, the sorting happens here and here

houkanshan avatar Feb 20 '24 23:02 houkanshan

What about sorting suggestions by popularity?

When you already imported useQuery a bunch of times from react-query in your current project, it probably makes sense to suggest that over a useQuery exported from a module that you have never used.

There can also be other heuristics, but this feels like a good start.

I feel I could forgive having to click an obtuse option once or twice but some general user popularity score would be really nice. This should be the goal IMO. Then this should also feed into the selection process for "Add All Missing Imports".

Alternatively, maybe something we can just put in .vscode/settings.json where you can just add a suggestion blacklist.

timreach avatar Oct 02 '24 12:10 timreach

I think also closest relative should be first, and prefer down the tree before up the tree. trying to import a B while in ./A/x.ts

should prefer this order: ./b.ts ./b/b.ts ./b/b/b.ts ../b.ts ../B/b.ts ../B/b/b.ts some_ts_path/* @some_npm_package/*

patroza avatar Oct 09 '24 13:10 patroza

this has been driving me insane. everytimes vscode autoimports a component it crashes my dev server because it is always import the node module and not my local aliased module. is there not a workaround for this?

odama626 avatar Nov 23 '24 00:11 odama626

You can change the auto-complete suggestions and code fix (quick fix) with a TypeScript Plugin. A TypeScript Plugin has to be a package (cannot be a local file), so I made one: https://github.com/tidalhq/ts-plugin-sort-import-suggestions

image

If you are interested, the sorting happens here and here

Thanks, it works great! I just wrote a step-by-step guide so it’s easier if someone needs to implement this. Hopefully it helps.

https://theodorusclarence.com/shorts/vscode/auto-import-sort

theodorusclarence avatar Dec 04 '24 06:12 theodorusclarence

You can change the auto-complete suggestions and code fix (quick fix) with a TypeScript Plugin. A TypeScript Plugin has to be a package (cannot be a local file), so I made one: https://github.com/tidalhq/ts-plugin-sort-import-suggestions

If you are interested, the sorting happens here and here

This is great, and works with the in-file suggestions. But for auto completion on saves it doesn't work for some reason?

  "editor.codeActionsOnSave": {
    "source.addMissingImports": "always",
  }

I guess this uses the VSCode typescript and not from the workspace.

itzaks avatar Mar 07 '25 16:03 itzaks

We really need this feature for monorepo projects...

HirokiTakekuma avatar Mar 20 '25 04:03 HirokiTakekuma

Bumping this one, would be a huge productivity booster for our team

mchlkucera avatar Apr 18 '25 06:04 mchlkucera

+1 for this issue

akodkod avatar Aug 07 '25 12:08 akodkod

I'd also like to +1 this issue.

I would definitely like to be able to trust my add missing imports context menu option again. I'm currently working on a pretty intense merge right now. In the upstream we've wrapped a function from an npm package with our own function of the same name that customizes the behavior, sets sane defaults, etc. for our needs. Now I have to manually import our wrapper function before I can trust add missing imports

Unfortunately, a lot of this is going to bleed into IDE behaviors, but maybe a temporary work around would be to auto-import everything it can find and let us remove the incorrect duplicates...

dallenbaldwin avatar Aug 28 '25 16:08 dallenbaldwin

Another issue I always face is auto import from src/ instead of dist/ in a monorepo where stuff is import d directly from files instead of the index

adrian-gierakowski avatar Aug 29 '25 14:08 adrian-gierakowski