I have the following project structure:
- root
- src
- scripts
- main.js
- foo.js
- scripts
- src
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?
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 calledsrc
.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.