Rachid O
Rachid O

Reputation: 14002

Shortcut for automatic import of a class in WebStorm for TypeScript

I was watching a tutorial video of Angular2 and the guy typed @Injectable() then with some black magic a line appeared on top

import {Injectable} from 'angular2/core'

How did he do this, what type of sorcery is this ?

Upvotes: 4

Views: 2636

Answers (2)

Negin
Negin

Reputation: 2394

This is one of the greatest shortcuts in WebStorm editor.

Following below steps:

  • Open WebStorm code editor.
  • Preferences
  • Editor
  • General
  • Auto Import
  • Mark : show Import Pop up
  • Mark : Merge imports for symbols from the same module.

Ok.

Imagine you want to use Validators in your form. You are typing Validators.required and then it shows the Validators word in red colour because it needs to be imported to the angular/forms.
Double click on the word and press option+enter. it automatically imports:

import {Validators} from "@angular/forms";

The reason that I asked you to also mark : Merge imports for symbols from the same module is:

Imagine you have already imported Validators from @angular/forms and now you want to add FormGroup which also needs to be imported from @angular/forms. What is happening now is it does not add another extra import line for each of them separately but is just adding to the available one.

import { Validators , FormGroup } from "@angular/forms"

Upvotes: 0

LazyOne
LazyOne

Reputation: 165168

He (John Lindquist) used Alt + Enter (the shortcut in Default keymap -- may differ if you're using different keymap) to bring the Quick Fix menu (also can be triggered by clicking on light bulb icon).

Once menu is shown he used "Add import statement" entry (quick fix) from that menu.


RE: keymap -- you may check and assign different shortcut for that menu -- just use Settings/Preferences | Keymap and look for Show Intention Actions action (hint: use search boxes to quickly narrow the list).

Upvotes: 5

Related Questions