Tips & Tricks

Optimize Imports in WebStorm

To help you keep the import section in a JavaScript or a TypeScript file clean and readable, WebStorm has an action called Optimize imports. It does several things at once:

  • it removes any imports that are no longer used;
  • it merges together multiple imports from the same file;
  • it can sort members inside the import and sort imports by the module name.

To run Optimize imports, use the shortcut Ctrl-Alt-O or find it in the Find Action popup (Cmd/Ctrl-Shift-A). Alternatively, you can just have WebStorm run it automatically before a commit. We’ll talk about ways to do that in a second.

Here’s how Optimize imports works:

Let’s have a closer look at the actual code:

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // FormsModule is no longer used,
// so we can remove its import

import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';
import { ApplicationInitStatus } from '@angular/core'; // this one imports from 
// the same module as the one above, so they can be merged into one import

This is what we get after running Optimize imports with the default options:
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { ApplicationInitStatus, NgModule } from '@angular/core';

If we want to go one step further and also sort the imports, we can do that by going to Preferences | Editor | Code Style | TypeScript or JavaScript and checking Sort imports by modules on the Import tab. This will sort our imports alphabetically by module name (the part after from):
import { ApplicationInitStatus, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

On this tab, you can also find two other options related to Optimize import: Merge imports for members from the same module and Sort imported members (responsible to sorting symbols inside {} in the import statement).


There are several ways how you can run Optimize imports.

The most straightforward way to use the Optimize import action is to press Ctrl-Alt-O or find it in the Find Action popup (Cmd/Ctrl-Shift-A). This will only change imports in the currently opened file.

You can also select a folder in the Project view and press the same shortcut – this will run Optimize imports for all the files in this folder.


Notice the check-box that says, Process only VSC changed files on the confirmation dialog. As you might guess, if you check it, the imports will be updated only in those files that are not yet committed to the version control.

Talking about version control, you can enable Optimize imports in the Commit Changes dialog – this will optimize imports in all the files that you have selected for your commit.


The WebStorm team