JavaScript: use both absolute and relative import paths

When importing JS modules, is it possible to use relative path for files in the same directory and absolute paths for all other cases? If not, are you aware of any plugin that may help? Or should I sumbit proposal to some issue tracker of yours?


Details:
Consider following project structure:

src/
    dirA/
        dirB/
            fileB.js
        fileA1.js
        fileA2.js
    dirC/
        fileC.js

where "src/" is marked as "Sources Root".
What I want to achieve are following imports inside fileA1.js:

import ... from "dirA/dirB/fileB"
import ... from "./fileA2"
import ... from "dirC/fileC"

or at least

import ... from "./dirB/fileB"
import ... from "./fileA2"
import ... from "dirC/fileC"

Available configuration
File -> Settings -> Editor -> CodeStyle -> JavaScript -> Imports -> "Use paths relative to the project, resources or sources root"
is of course not sufficient:
1) Option checked:

import ... from "dirA/dirB/fileB"
import ... from "dirA/fileA2"
import ... from "dirC/fileC"


2) Option unchecked:

import ... from "./dirB/fileB"
import ... from "./fileA2"
import ... from "../dirC/fileC"
3 comments
Comment actions Permalink

When using webpack aliases for absolute paths, setting Use path aliases in Settings | Editor | Code Style | JavaScript | Imports to Only in files outside specified paths allows using relative paths for files within aliased paths

0
Comment actions Permalink

We have the same requirements. We prefer the relative imports when importing from the same folder and absolute imports when importing from a location outside the current folder. This matches the scenarios described in this ticket.

2
Comment actions Permalink

In my case I solved the issue by adding a jsconfig.json file with the following content

{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}

 

-1

Please sign in to leave a comment.