Path aliases for imports in WebStorm
Asked Answered
U

12

106

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?

Unpeopled answered 22/1, 2016 at 9:50 Comment(0)
C
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 ...

Cullet answered 10/5, 2016 at 9:54 Comment(15)
this will effectively break things when not directly building from WebstormHunk
Why is that ? If you keep the aliases in your Webpack configuration ... Actually we do build outside of Webstorm without any problem ...Cullet
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"Unpeopled
I'ver tried in WebStorm 2016.2.3, but this solution doesn't work.Derrek
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?Zarger
@Derrek I'm using Webstorm 2016.2.3 and it works pretty well. What problem do you have exactly ?Cullet
Don't forget to mark PARENT folder, not the starting folder of your path.Slop
Yes. I've just bolded it.Cullet
deprecated answer. Starting since WS2017.2 webstorm automatically parses and applies Webpack configCursor
I added a deprecation notice.Cullet
@Cursor I installed the Webstorm EAP 2017.2 and it still cannot figure out my aliases. Do I have to do something?Marvelofperu
@Marvelofperu see this blogpost blog.jetbrains.com/webstorm/2017/06/…Cursor
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" blog.jetbrains.com/webstorm/2017/06/…Tun
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.Dislocate
@Zarger see https://mcmap.net/q/203433/-path-aliases-for-imports-in-webstormElasmobranch
O
80

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

enter image description here

Ovotestis answered 28/8, 2017 at 8:38 Comment(5)
It works. The file should include module.exports = {resolve: {alias: {'@utils': path.resolve(__dirname, '../utils/')}}}. Also I had to restart WebStorm to apply the changes.Novelistic
Thanks! It helped me in PhpStorm 2019.1Succursal
We should mark this answer to the best answer. Thanks.Arnulfoarny
this one helped meTamarau
Thanks! Finally some solution for this annoying problem.Apathy
S
54

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.

Staphyloplasty answered 17/12, 2019 at 6:56 Comment(7)
This actually works! Really helped me with the project on Rollup+Svelte!Retuse
thanks. it works. Q: Do you know any documentation for full options available for this file ?Peppel
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.Maggi
This should be the best answer. Thank you very much.Iodous
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.Moten
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: #71553072Ell
Thanks for this workaround. I can't find where does this System global comes from, anyone has docs to it ?Diversion
T
47

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

Twodimensional answered 3/5, 2018 at 16:2 Comment(1)
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.Dislocate
M
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.

Mossbunker answered 1/12, 2017 at 21:24 Comment(6)
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.Anomie
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!Anomie
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.Mossbunker
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!Anomie
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 advertisedAleen
Using the dev webpack config worked for me. Thanks!Durant
C
9

Add jsconfig.json to your projects source root:

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

Further reading: What is jsconfig.json?

Constituent answered 26/11, 2020 at 0:42 Comment(2)
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.Evenfall
2024: fixing up outdated jsconfig.json files was the key to success in our monorepo. paths keys had become stale with directory structure migration PRs overlooking updating them.Lovely
B
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.

Banas answered 23/1, 2016 at 13:30 Comment(1)
This is the better answer. Relative paths are annoying, but the convenience of path aliases is not worth losing useful IDE functionality.Zucchetto
A
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.

Acetal answered 10/8, 2017 at 16:59 Comment(0)
K
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')
}
Karyn answered 28/4, 2018 at 12:41 Comment(2)
How do you get Webstorm to recognize @someAlias correctly?Neibart
Where file you defined alias? In which file?Penicillium
C
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.

Covey answered 13/1, 2019 at 9:29 Comment(0)
T
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.

Trope answered 6/1, 2022 at 12:44 Comment(1)
Love your perfectionism. I'd do it identically (no joke).Ribbon
E
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
Elmiraelmo answered 4/1, 2022 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.