102

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?

Evan Wieland
  • 1,445
  • 1
  • 20
  • 36
Bogdan D
  • 5,321
  • 2
  • 31
  • 32

12 Answers12

145

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 ...

Jalil
  • 3,150
  • 3
  • 30
  • 39
  • 3
    this will effectively break things when not directly building from Webstorm – maddrag0n May 17 '16 at 13:46
  • Why is that ? If you keep the aliases in your Webpack configuration ... Actually we do build outside of Webstorm without any problem ... – Jalil May 17 '16 at 15:15
  • I haven't tested it yet, but the answer makes total sense. It was exactly what I was looking for when I asked the question. Thanks, @Jalil, I'm marking your answer "accepted" – Bogdan D May 18 '16 at 15:54
  • 2
    I'ver tried in WebStorm 2016.2.3, but this solution doesn't work. – Zation Sep 25 '16 at 13:27
  • 3
    and what about imports in angular2 `import { Component } from '@angular/core'`, that is resolved too. How can I implement the `at` to make more clear that path is an alias? – Hitmands Oct 03 '16 at 13:49
  • @Zation I'm using Webstorm 2016.2.3 and it works pretty well. What problem do you have exactly ? – Jalil Oct 03 '16 at 17:18
  • Don't forget to mark PARENT folder, not the starting folder of your path. – lima_fil Feb 12 '17 at 00:29
  • Yes. I've just bolded it. – Jalil Apr 01 '17 at 10:29
  • deprecated answer. Starting since WS2017.2 webstorm automatically parses and applies Webpack config – anstarovoyt Jun 19 '17 at 13:38
  • I added a deprecation notice. – Jalil Jun 26 '17 at 14:58
  • @anstarovoyt I installed the Webstorm EAP 2017.2 and it still cannot figure out my aliases. Do I have to do something? – Toosick Jul 03 '17 at 23:44
  • 7
    @Toosick see this blogpost https://blog.jetbrains.com/webstorm/2017/06/webstorm-2017-2-eap-172-2827/ – anstarovoyt Jul 04 '17 at 10:51
  • 3
    What about multiple folders and multiple webpack configs? Doesn't work for me maybe because of this: "By default WebStorm will analyse the webpack configuration file in the root of the project, but you can select another file in Preferences | Languages & Frameworks | JavaScript | Webpack" https://blog.jetbrains.com/webstorm/2017/06/webstorm-2017-2-eap-172-2827/ – rofrol Jul 19 '17 at 13:45
  • Don't rush to deprecate this answer. Accumulating experience shows that JetBrain's support for parsing Webpack config is fragile to the point of unusability. Old tricks must unfortunately still be used. – Szczepan Hołyszewski Dec 13 '20 at 18:59
  • @Hitmands see https://stackoverflow.com/a/59369029/12208030 – lyh543 Nov 23 '21 at 09:13
81

I managed to set up aliases for WebStorm 2017.2 within webpack like this:

enter image description here

Evan Wieland
  • 1,445
  • 1
  • 20
  • 36
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
48

You can define custom paths, so WebStorm/PhpStorm can understand your aliases. But make sure, they are identical with your aliases. Create file in your root directory and call it something like this: webStorm.config.js (any js file will be ok). Then configure your paths inside:

System.config({
  "paths": {
    "components/*": "./src/components/*",
    "core/*": "./src/core/*",
    ...
  }
});

WebStorm/PhpStorm will recognize System as it's own module and will treat this file as configuration.

E. Dn
  • 940
  • 1
  • 9
  • 21
  • 2
    This actually works! Really helped me with the project on Rollup+Svelte! – joycollector Mar 28 '20 at 07:40
  • 2
    thanks. it works. Q: Do you know any documentation for full options available for this file ? – Mojtaba Hn Aug 16 '20 at 15:51
  • Is there a way to do this for a specific js file? So for example, I'd like to use "config" in place of "src/server/lib/config/index.js". I tried `"config": "./src/server/lib/config/index.js"` but that didn't work. – Matt Jan 22 '21 at 20:16
  • This should be the best answer. Thank you very much. – Nhan DT May 10 '21 at 04:57
  • Awesome! Unfortunately, I also have to manually configure ESLint and Rollup with duplicates of the aliases. At least I have a clean environment, but I wish JetBrains would support Rollup natively like they do Webpack. – Mac Jun 17 '21 at 16:03
  • Thank you for posting this! This also works for the special `$lib/*` references in SvelteKit. A copy/paste answer for that can be found here: https://stackoverflow.com/questions/71552572/how-to-enable-support-for-sveltekits-lib-alias-in-webstorm-and-phpstorm-etc/71552573 – patricknelson Mar 21 '22 at 03:45
  • Thanks for this workaround. I can't find where does this System global comes from, anyone has docs to it ? – Apolo Aug 08 '23 at 09:02
45

For the record: in PHPSTORM, working with laravel mix, I managed to solve this by creating a webpack.config.js file separately like:

const path = require('path')
const webpack = require('webpack')

module.exports = {
  ...
  resolve: {
    extensions: ['.js', '.json', '.vue'],
    alias: {
      '~': path.resolve(__dirname, './resources/assets/js')
    }
  },
  ...
}

And then importing it in the webpack.mix.js like:

const config = require('./webpack.config')
...
mix.webpackConfig(config)

Make sure the webpack configuration file is pointed correctly in the configuration of the PhpStorm in: Settings > Languages & Frameworks > Javascript > Webpack

nachodd
  • 703
  • 6
  • 7
  • 4
    Please consider the situation of users who don't actually use webpack in their project, and want to set up those two files SOLELY for the purpose of teaching PHPStorm how to resolve aliases. Those people won't know what should go in the "..." in order to make the webpack.mix.js file actually working for this purpose. Specifically, if I simply remove "...", the `mix` symbol is reported as unresolved by the IDE, which is a strong hint that it won't actually work. There are missing but critically important lines where the "mix" symbol is somehow required/imported. Please add those to your answer. – Szczepan Hołyszewski Oct 16 '20 at 19:15
13

This is answered in a comment but to save people digging into comments and link only information, here it is:

As of WS2017.2 this will be done automatically. The information is here.

According to this, webstorm will automatically resolve aliases that are included within the webpack.config in the root of the project. If you have a custom structure and your webpack.config isn't in the root folder then go to Settings | Languages & Frameworks | JavaScript | Webpack and set the option to the config you require.

Note: Most setups have a base config which then call a dev or prod version. In order for this to work properly, you need to tell webstorm to use the dev one.

webnoob
  • 15,747
  • 13
  • 83
  • 165
  • 2
    This seems to work unless a Webpack alias is used. I am using `@` as an alias to my `src` folder, but even after pointing Webstorm to my config, it still would not resolve my imports correctly. However, once I marked the `src` folder as Resource Root, it worked as expected. Would be nice if Webstorm could handle aliases, but no big deal. – dericcain Jan 08 '18 at 13:41
  • Are you using a symbol for an alias like so: `'@': '../src')`. Also, are you using one file for your webpack config, or multiple? Wondering what is different. Thanks! – dericcain Jan 08 '18 at 14:41
  • 3
    One example of mine is `'@': path.resolve(__dirname, '../src/components')`. I use multiple files, `webpack.base.conf.js` then `dev` and `prod` versions. They in turn call a config folder with `index.js`, `dev.env.js` and `prod.env.js`. I point my webstorm to look at the `webpack.dev.conf.js` file. – webnoob Jan 08 '18 at 14:47
  • 2
    My setup is very similar (vue-webpack-pwa) and pointing it to the `.dev.conf` did the trick. Pointing to the `.base.conf` was not working. Good call! – dericcain Jan 08 '18 at 16:46
  • I think this may need an issue to be opened. I can confirm it works but oftentimes I'll open it and all of the webpack aliases are unresolved. I do an "Invalidate Caches and Restart" , and it works as advertised – willredington315 Dec 06 '18 at 13:58
  • Using the dev webpack config worked for me. Thanks! – Kevin Bruccoleri Oct 07 '19 at 01:30
6

Not right now, We were also using path aliases for the files in our react project. The import names were shorter but we lost a lot on static checking of webstorm as well as completion features.

We later came up with a decision to reduce the code to only 3 levels of depth, as well a single level for the common parts. The path completion feature of webstom (ctrl + space) even helps reduce the typing overhead. The production build does not use longer names, so hardly makes any difference in final code.

I will suggest please reconsider your decision about aliases. You loose semantic meaning of modules coming from node_modules and your own code, as well as referencing the alias files again and again to make sense of your code, is a much bigger overhead.

sandeep
  • 2,098
  • 1
  • 10
  • 13
  • 1
    This is the better answer. Relative paths are annoying, but the convenience of path aliases is not worth losing useful IDE functionality. – thewoolleyman Jun 23 '17 at 16:19
6

add jsconfig.js on your project root

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./src/*"]
    }
  }
}

keating
  • 327
  • 4
  • 4
  • This worked for me after restarting webstorm. This is a good option for people not using webpack and therefore don't have a webpack config with aliases. People using typescript will have these same settings in your tsconfig.json file but you'll still need this jsconfig.json to get the alias's working in .js and .jsx files. – Aaron Solberg Jan 10 '23 at 18:47
3

In PHPStorm (using 2017.2 currently), I have not been able to get webpack configs to work properly in regards to aliases.

My fix involves using the "Directories" section of the main settings. I just had to mark each folder referenced by an alias as a sources root, then click the properties dropdown for each and specify the alias as a "Package prefix". This made everything link up for me.

Not sure if the Directories section exists in WebStorm, but if it does, this seems to be a fool-proof method for getting import aliases working.

Evan Wieland
  • 1,445
  • 1
  • 20
  • 36
Gordon Forsythe
  • 356
  • 3
  • 7
2

For anyone struggling: path.resolve() must be called with "__dirname" first argument for Idea (Websorm) to be able to resolve the path correctly.

Will work for Idea (Websorm):

alias: {
    '@someAlias': pathLib.resolve(__dirname, 'path/to/directory')
}

Will not work for Idea (Websorm) (while still being valid webpack alias):

alias: {
    '@someAlias': pathLib.resolve('path/to/directory')
}
Kshatra
  • 369
  • 1
  • 4
  • 12
2

Webstorm can't read webpack.config if module.exports return a function. For example

module.exports = function (webpackEnv) {
  return {
    mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
    ...
 }
}

Check your config file, maybe this cause you are a problem.

hong4rc
  • 3,999
  • 4
  • 21
  • 40
2

There is a lot of discussion here about Laravel Mix, so I'll leave this here to help out future readers. I solved this by creating a separate (fake) webpack config file which is only used by my IDE (PHPStorm).

1. Create a separate alias.js file (e.g. /webpack/alias.js)

const path = require('path');

const assets = path.join(__dirname,'..','resources','assets');

module.exports = {
    '@js'        : path.resolve(assets, 'js'),
    '@c'         : path.resolve(assets, 'js', 'components'),    
    '@errors'    : path.resolve(assets, 'js', 'errors'),
    '@utils'     : path.resolve(assets, 'js', 'utils'),
    '@store'     : path.resolve(assets, 'js', 'store'),
    '@api'       : path.resolve(assets, 'js', 'api'),
    '@less'      : path.resolve(assets, 'less')
}

2. Require the alias.js file into webpack.mix.js

const mix  = require('laravel-mix');

mix.alias(require('./webpack/alias'))
   // ... The rest of your mix, e.g.
   .js('app.js')
   .vue()
   .less('app.less');

3. Create the fake webpack config for your IDE (e.g. /webpack/ide.config.js)

Here, import the laravel-mix webpack config, plus your aliases, and any other config that the IDE might need help finding. Also include the prefixed ~ aliases for importing styles into your Vue components.

/*
 |--------------------------------------------------------------------------
 | A fake config file for PhpStorm to enable aliases
 |--------------------------------------------------------------------------
 |
 |   File > Settings... > Languages & Frameworks > Javascript > Webpack
 |
 |   Select "Manually" and set the configuration file to this
 |
*/
const path = require('path');
const mixConfig = require('./../node_modules/laravel-mix/setup/webpack.config')();

module.exports = {
    ...mixConfig,
    resolve: {
        alias: {
            ...require('./alias'),
            '~@less' : path.resolve('@less'), // <-- 
        },
        ...mixConfig.resolve
    }
}

4. Set your IDE to use webpack/ide.config.js as your webpack config file.

Erin
  • 5,315
  • 2
  • 20
  • 36
0

Had the same problem on a new Laravel project with Jetstream. The webpack.config.js was present and correct. But PHPStorm still didn't recognize the @ symbol as a resource root.

After opening the webpack config, I got a notification:

PHPStorm notification

After Clicking on Trust project and run, the @ symbol became recognized.

I know that this isn't the solution or use-case for everyone. But I still found it worthy to note on this post, because it helped me in my situation.

Using

  • laravel/framework:8.77.1
  • npm:8.3.0
  • node:v14.18.1
Mark Walet
  • 1,147
  • 10
  • 21