24

I'm doing various projects in React.js with using awesome WebStorm by JetBrains.

Every time I type an existing component name WebStorm imports it automatically for me, which is awesome, but it is doing so by its relative path based on the file I'm doing the importation on.

Looks like so:

import vintageAxios from "../../../../services/api/index";

But I'm expecting it to be like:

import vintageAxios from "services/api/index";

I already setup my .env.local file with the NODE_PATH=src/ variable, I've used create-react-app to setup the project.

EDIT: I'm not having problems with the importations. What I want to know is if there is a way to configure WebStorm so it automatically does the importations with absolute instead of relative paths.

Cristian Rojas
  • 2,746
  • 7
  • 33
  • 42

2 Answers2

40

Found it (WebStorm 2017.2), after marking your source directory (ex. /src) as the source root (right click it to find that), you can then check this box:

enter image description here

ABCD.ca
  • 2,365
  • 3
  • 32
  • 24
  • 5
    Works like a charm! I needed to mark my `src` directory as "resource root" and it is doing the magic now! – Cristian Rojas Oct 03 '17 at 16:02
  • 6
    If you're using typescript. It's Code Style/Typescript – henkieee Aug 07 '18 at 11:05
  • None of the advice here works for me. Using WebStorm 2020.3, `src` marked as Resource root, Javascript code style `Use paths relative to the project` is _unchecked_, TypeScript code style `Use paths relative to tsconfig.json` _unchecked_, EditorConfig disabled. Still imports files as `../../../../../../../this/drives/me/crazy/`. Any ideas? – JHH Apr 22 '21 at 15:16
  • 1
    Ok wow, so I misunderstood those checkboxes. To use paths relative to tsconfig.json _is what I want_, in order to avoid _relative paths from each file_. Not the best wording on that setting perhaps, or I'm just a sloppy reader today. – JHH Apr 22 '21 at 15:18
  • 3
    I have the exact opposite problem. I want relative imports, but WebStorm insists on absolute imports. Toggling the settings in WebStorm has no effect. My tsconfig.json doesn't specify a `baseUrl`, yet WebStorm acts as if it is. – Steve Jul 24 '21 at 00:30
  • tried the above solution for my react javascript project and it just doesn't work. Also not only autocompletion doesn't work but the whole import doesn't work (Module not found).I'm using Webstorm 2022.1.3 . – Rafael Santos Jun 29 '22 at 06:52
10

For anyone using Typescript. Check the option Use paths relative to tsconfig.json in Editor > Code Style > Typescript

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230