gameveloster
gameveloster

Reputation: 1513

Auto-import Javascript module in Vscode using Shortcut (Ctrl + .)

If my JS code uses a module/varaible that is not yet imported, VSCode will underline it in red

Image showing underline in VSCode

How can VSCode be configured such that we can select the unimported variable, either press a shortcut or select something from the right-click menu, and select the appropriate module to be imported.

Similar to the Ctrl + . auto-import shortcut when dealing with Rust files

Upvotes: 9

Views: 35310

Answers (2)

Tom
Tom

Reputation: 9127

Create a clone of the Rust shortcut

Since there is already a shortcut that does what you want (albeit in a different language), you may be able to create a new shortcut based on the existing one.

First: open your keyboard shortcuts, and do a "reverse-shortcut" search for Ctrl + .. There's an icon near the right side of the search input that switches the search behavior to this:

Search by keys icon

You may find multiple matches; study them to identify the Rust import command that you like. In particular, take note of the "Source" column: if Source is "Extension," that means you're getting the Rust behavior from an extension, and you may need to find (or create) a similar extension that targets JS/TS. (I suspect you will, because I don't have any commands related to imports in my VSCode.) The next step requires that you copy the value of the Where column, so do that now.

Second: look at the "Command" column for the name given to this behavior. If the name is specific to Rust, do a new search for a similar command that doesn't target Rust. If there is such a command, you just need to configure it to run when you like: edit that shortcut and paste the "When" value from behavior; this may require a hand-edit if the When from the Rust command mentions anything specific about Rust (e.g. if it includes editorLangId == 'markdown', change that to 'javascript' and add alternative for typescript as well).

If there is no auto-import command that is language agnostic, and none that is specific to JS/TS (again, I don't see one in my VSC), you will have to rely on the Intellisense-based option, or find (or create) an extension that does this. Creating an extension is a whole other topic.

Upvotes: 3

Viradex
Viradex

Reputation: 3748

Normally, in Visual Studio Code, if you type in a variable or function that isn't imported, then Visual Studio Code will auto-correct it, if you select it.

For example, if I am typing half the name of a function, it will infer that I want a function, and when I hit Tab/Enter, it will autocomplete it, and import it.

See the GIF below for a visual example.

Example GIF

Upvotes: 5

Related Questions