IntelliJ/Webstorm not finding import reference

4.7k views Asked by At

I have the following project structure:

  • root
    • src
      • scripts
        • main.js
        • foo.js

Inside of my main.js file, I'm importing foo.js like so:

import 'src/scripts/foo.js'

When I click on the import statement above and go to Navigate -> Declaration I get a super helpful message that says Cannot find declaration to go.

This makes it super frustrating to work with because the editor basically has no idea which files import other files. This means I can't use the helpful features of the IDE like search for references when moving a file, find usages, etc

If I change the import statement to be relative, it works altogether:

import './foo.js'

However, we are striving for absolute imports, a habit we picked up from writing python apps.

I came across Webstorm: "Cannot Resolve Directory" and that gave me the idea to mark my src directory as a Sources Root. After doing that, I could change my import statement in main.js to

import '/scripts/foo.js' //notice the leading forward slash

Well, that's a little better because now I can at least Navigate -> Declaration but it's not ideal because now I can't mark any of the directories underneath src as a test, resource, etc.

So why is IntelliJ/webstorm making this so difficult to do?

2

There are 2 answers

2
loganfsmyth On BEST ANSWER

I would very much suggest against using this style of import in JavaScript code. While potentially workable, relative paths are the defacto standard in all NodeJS code, and that has spread to essentially all JS code that uses module systems.

In current systems, any path starting with . is relative, any path starting with / is absolute, and any other path is resolved to a module. By that logic, import 'src/scripts/foo.js' would be parsed as ./scripts/foo.js relative to a dependency module called src.

Note also that the file extension is optional and commonly left off.

If you want to use this style and your module loader supports it, you are of course free to do so, but I want to stress that you are likely bringing pain upon yourself by using a non-standard approach.

2
Darek Kay On

Because now I can't mark any of the directories underneath src as a test, resource, etc.

Yes, you can. It is not possible to mark subfolders of already marked folders in the Project View. But you can do this in Project Structure (Ctrl + Shift + Alt + S). Go to Modules, select your module and switch to the Sources tab. Now you can mark your src folder as Sources (which you already did) and mark src/test as Tests etc.

According to the Web Help, in WebStorm this setting is hidden in Settings > Directories instead of the Project Structure.

Here's another solution using only the Project View: unmark your source folder, mark your test/resource subfolders and then mark the (parent) source folder again. I'm not sure, why it doesn't work the other way around.