Path aliases for imports in WebStorm

Bogdan D picture Bogdan D · Jan 22, 2016 · Viewed 43k times · Source

I use webpack path aliases for ES6 module loading.

E.g. If I define an alias for utils instead of something like
import Foo from "../../../utils/foo", I can do
import Foo from "utils/foo"

The problem is that once I start using aliases, WebStorm looses track of the import and I'm left with warnings and no auto-completion.

Is there a way to instruct WebStorm to use such aliases?

Answer

Jalil picture Jalil · May 10, 2016

[Deprecated answer. Starting since WS2017.2 Webstorm automatically parses and applies Webpack config (see @anstarovoyt comment)]

Yes, there is.

In fact, Webstorm can't automatically parse and apply Webpack config, but you can set up aliases the same way.

You just have to mark the parent folder of "utils" (in your example) as a resource root (right-click, mark directory as / resource root).

right click on folder

We just managed to do with the following structure :

/src
    /A
    /B
    /C

We have A B and C folders declared as alias in Webpack. And in Webstorm we marked "src" as "Resource Root".

And now we can simply import :

import A/path/to/any/file.js

instead of

import ../../../../../A/path/to/any/file.js

while still having Webstorm correctly parsing and indexing all code, link to files, autocompleting and so on ...