DEV Community

Cover image for Tired Of Relative Imports? Time To Get Rid Of Them!
Ludal ๐Ÿš€
Ludal ๐Ÿš€

Posted on • Edited on • Originally published at iamludal.fr

Tired Of Relative Imports? Time To Get Rid Of Them!

At some point in your Javascript developer journey, you've certainly encountered these types of imports:

import Car from '../../../vehicles/car'
import House from '../../../buildings/house'
Enter fullscreen mode Exit fullscreen mode

And you were probably bothered by the ugliness of them...

https://media.giphy.com/media/3o8doVY3jacRLyrSmI/giphy.gif

But guess what? I'm here as a savior to show you how to get rid of them! (really) ๐Ÿ˜Ž

Ready? Let's go! ๐Ÿ

baseUrl

The simplest way to get rid of these awful imports is by simply editing your jsconfig.json file. If you don't already have one, you can just create it at the root of your project.

Let's complete it with the following keys:

{
    "compilerOptions": {
        "baseUrl": "."
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, the most studious ones of you might think: "Compiler options? But JavaScript is not a compiled language!". And you're right! If you want to know why does this key exist, I recommend you to follow this link from the official website of Visual Studio Code.

Now, imagine having the following directory structure:

.
โ”œโ”€โ”€ components
โ”‚   โ””โ”€โ”€ layouts
โ”‚       โ””โ”€โ”€ header.js
โ”œโ”€โ”€ styles
โ”‚   โ””โ”€โ”€ header.css
โ””โ”€โ”€ jsconfig.json
Enter fullscreen mode Exit fullscreen mode

If you want to include your header.css style file in your header.js file, you can now do it this way:

// header.js
import 'styles/header.css'
Enter fullscreen mode Exit fullscreen mode

Without this configuration, here's how you would have done it:

// header.js
import '../../styles/header.css'
Enter fullscreen mode Exit fullscreen mode

Now, no matter how deep you are in your project's architecture, you'll be able to import your files as if you were at the root of your project. ๐Ÿ˜ฒ

And obviously, you'll still able to import them relatively from the current directory you are in!

.
โ”œโ”€โ”€ src
โ”‚   โ”œโ”€โ”€ vehicles
โ”‚   โ”‚   โ””โ”€โ”€ car.js
โ”‚   โ”‚   โ””โ”€โ”€ truck.js
โ”‚   โ””โ”€โ”€ index.js
โ””โ”€โ”€ jsconfig.json
Enter fullscreen mode Exit fullscreen mode

// index.js
import truck from './vehicles/truck.js'
Enter fullscreen mode Exit fullscreen mode

https://media.giphy.com/media/oYtVHSxngR3lC/giphy.gif

Paths

Back to our jsconfig.json. You can also add the paths key in order to map an import to a specific folder. This is useful for giving aliases to some folders in your imports.

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "css/*": ["styles/*"]
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Considering the same folder structure we've seen in the previous part, you could now import your styles like this:

// header.js
import 'css/header.css'
Enter fullscreen mode Exit fullscreen mode

But I wouldn't recommend doing this at all, as this would create inconsistencies between the real folders' names and the aliases โ€” instead, why not simply renaming the actual folder? ๐Ÿคจ

Nevertheless, this option can be useful for folders you often use and that are not at the root of your project. Let's consider the following structure:

.
โ”œโ”€โ”€ assets
โ”‚   โ”œโ”€โ”€ styles
โ”‚   โ”‚   โ””โ”€โ”€ index.css
|โ”€โ”€ src
โ”‚   โ””โ”€โ”€ index.js
โ””โ”€โ”€ jsconfig.json
Enter fullscreen mode Exit fullscreen mode

We will often use the styles directory to import our styles, and that could be very handy if we could remove the assets prefix, in order to not have to always write this:

import 'assets/styles/index.css'
Enter fullscreen mode Exit fullscreen mode

In that case, you could add the following to your jsconfig.json:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@styles/*": ["assets/styles/*"]
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

After that, here's how you would import your styles:

import '@styles/index.css'
Enter fullscreen mode Exit fullscreen mode

The @ is a conventional way to reference a folder-mapping import, in order to differentiate it from a classic import.

TypeScript

Oh, you are using TypeScript? Awesome! Of course you can also use this trick: the only difference is that you won't write those settings inside the jsconfig.json file, but instead, inside...?

https://media.giphy.com/media/3o7TKTDn976rzVgky4/giphy.gif

Exactly! Inside the tsconfig.json file. Smart, isn't it? ๐Ÿ˜

Conclusion

That's it! You've now got rid of those awful imports, congratulations! ๐ŸŽ‰

To go further, I would recommend you following this link from the official Visual Studio Code website, in particular to exclude some directories that are not part of the source code.

With that being said, I thank you for reading me all the way through, and I hope you've learned something with this article. ๐Ÿ˜Ž

https://media.giphy.com/media/3o6Zt6KHxJTbXCnSvu/giphy.gif

Top comments (17)

Collapse
 
valeriavg profile image
Valeria

While this method does work everywhere for TypeScript, it won't work for JavaScript without a bundler (especially NodeJS).
For NodeJS one could use NODE_PATH=./src node index.js to achieve similar results.

Collapse
 
adamcoster profile image
Adam Coster

This doesn't work for the JavaScript compiled by Typescript either, since the Typescript compiler doesn't rewrite import paths on compile. I ended up switching to Babel with the "Module Resolver" plugin for my Node projects (instead of using tsc) since being able to use path aliases is worth the annoyance of the extra dependency!

Collapse
 
christian102094 profile image
Christian Tapia

Spent several hours trying to configure it for Typescript. A real nightmare!

Thread Thread
 
valeriavg profile image
Valeria

Did you figure in the end? Otherwise try tsconfig-paths

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt

Can also be done with Babel, JavaScript also.

Collapse
 
heyprotagonist profile image
Anguram Shanmugam

now this post is perfect๐Ÿ‘

Collapse
 
iamludal profile image
Ludal ๐Ÿš€

Thanks! I'm always using it with React, so I didn't think about this point. ๐Ÿ™

Collapse
 
jcollum profile image
Justin Collum

This appears to be exclusive to VS Code. If so you should state that at the top.

Collapse
 
iamludal profile image
Ludal ๐Ÿš€

You're right! Or with a bundler? I'm using it with React. ๐Ÿค”

Collapse
 
prabhukadode profile image
Prabhu

Really useful

Collapse
 
big78113828 profile image
Big

in Create-React-App you can just edit your .env file and add

'NODE_PATH=src'

, assuming you're starting from the src/ folder.

Collapse
 
kettanaito profile image
Artem Zakharchenko

Path aliases are such a great feature, but setting it up on the TypeScript configuration level is not enough if you aim to reuse it across your devstack. I'm convinced there must be a higher medium to distribute alias settings, and that's why I'm pursuing the ".alias" project that allows you to defined path aliases and reuse them across all your tools (TypeScript, webpack, Jest, etc.):

github.com/open-draft/dotalias

Let me know what you think about it!

Collapse
 
gaurav5430 profile image
Gaurav Gupta

this works, but you also need to change settings in other tools used in your project which need module/path resolution. In my case, I needed to also enable this in webpack, storybook, jest, eslint

Collapse
 
iamludal profile image
Ludal ๐Ÿš€

You're right, I'm using it with React (CRA or Next.js), so I didn't think about it. ๐Ÿ™

Collapse
 
secretguard profile image
Info Comment hidden by post author - thread only accessible via permalink
Sarath G

Hello4

Collapse
 
secretguard profile image
Info Comment hidden by post author - thread only accessible via permalink
Sarath G

Hello3

Collapse
 
secretguard profile image
Info Comment hidden by post author - thread only accessible via permalink
Sarath G

Hello1

Some comments have been hidden by the post's author - find out more