How Pros Get Rid of Relative Imports
Tags: javascript, typescript, vscode, productivity
Published: 2021-09-12 04:59:37

If you have worked on a decently sized **Node.js** application regardless of whether its **JavaScript** or **TypeScript**, you will have come across long imports such as these:

```js
import User from "../../../../models/User";
```

which made you go:

![Astounded](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqfh00crbgyaqvy6uqbt.gif)

Rewriting long imports hundreds of times can get on anyone's nerves. This article with show you how to compress those long imports into compact and short imports. After all:

> Shorter Code == Happier Devs 😉

# Enter `jsconfig.json`

*What is `jsconfig.json`?* you might be asking. Well, `jsconfig.json` can be thought of as a **descendent** of `tsconfig.json`, with the `allowJs` attribute set to `true`.

In simple terms, `jsconfig.json` is a file that _specifies_ that the **directory is the root of a JavaScript project**. The `tsconfig.json` & `jsconfig.json` file specifies the **root files** and the **compiler options** required to **compile the project**.

For more on `jsconfig.json`, check out [this article](https://code.visualstudio.com/docs/languages/jsconfig).

For **Demonstration** purpose, we would be working on a **demo project** with the following file structure:

```
.
│   app.js
│   jsconfig.json
│   package.json
│   
├───models
│       user.js
│       
└───utils
    ├───colors
    │       converter.js
    │       generateColor.js
    │       
    └───datetime
            formatter.js
            timezoneHelpers.js
```

# Base Url

The easiest way to get rid of the long imports is to add `baseUrl` in the `jsconfig.json` (add `jsconfig.json` at the root level of the project in case you don't have it).

```json
{
    "compilerOptions": {
        "baseUrl": "."
    }
}
```

**Viola!** Now you can directly access the files and folders at the root level of your project. So to import _color_ related functions in the **User** model, you can now use:

```js
import { hexToRgb, rgbToHex } from 'utils/colors/converter'
```

in place of:

```js
import { hexToRgb, rgbToHex } from '../utils/colors/converter'
```

That's just a **minor improvement** in this demo, but in case your project has a lot of _nested folders_, it would lead to significant reductions.

But let's try to do better.

# Paths

**Paths** allow us to aggregate a **list directories** under a **predefined name** and _drastically reduce_ the **length of the imports**.

```json
{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@models/*": [
                "./models/*"
            ],
            "@colors/*": [
                "./utils/colors/*"
            ],
            "@datetime/*": [
                "./utils/datetime/*"
            ]
        }
    }
}
```

We are aggregating all the files in the `models` folder under the name `@models`. The same is the case for `colors` and `datetime`. We would be able to _reference the folders_ using `@models`, `@colors`, and `@datetime` in the import statement. So,

```js
import { hexToRgb, rgbToHex } from '../utils/colors/converter'
```

finally reduces to:

```js
import { hexToRgb, rgbToHex } from '@colors/converter'
```

**Somethings worth noting:**

1. The `pathname` _doesn't have to be the same_ as the actual **folder name**. But it's a **good idea** to _keep them the same_ to **avoid confusion**.
2. You can _aggregate as many folders_ you want under any `pathname`. Let's take a look at a bit absurd example:

    ```json
    "@colors/*": [
        "./utils/colors/*",
        "./utils/datetime/*"
    ]
    ```

    This would result in both the **datetime** and **colors** folders to be aggregated under the name `@colors`.

# TypeScript

Everything we went over can be used with **TypeScript** as well. Just replace `jsconfig.json` with `tsconfig.json` and you are done.

![Done](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nntrtcnd7p7oj8fpq5n2.gif)

NOTE: As [TalOrlanczyk](https://dev.to/talorlanczyk) pointed out in the comments, this doesn't work with `create-react-app`. The work-around is provided in the comments below.

# Wrapping up

This article went through how to **optimize** the _annoying long imports_ into _concise small statements_. I hope this helps you in your development journey! :)

Finding **personal finance** too intimidating? Checkout my **Instagram** to become a [**Dollar Ninja**](https://www.instagram.com/the.dollar.ninja/)

# Thanks for reading

Want to work together? Contact me on [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)

Want to see what I am working on? Check out my [GitHub](https://github.com/ruppysuppy)

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on [Instagram](https://www.instagram.com/tapajyotib/)

Follow my blogs for weekly new tidbits on [Dev](https://dev.to/ruppysuppy)

**FAQ**

These are a few commonly asked questions I get. So, I hope this **FAQ** section solves your issues.

1. **I am a beginner, how should I learn Front-End Web Dev?**
    Look into the following articles:
    1. [Front End Development Roadmap](https://dev.to/ruppysuppy/front-end-developer-roadmap-zero-to-hero-4pkf)
    2. [Front End Project Ideas](https://dev.to/ruppysuppy/5-projects-to-master-front-end-development-57p)

2. **Would you mentor me?**
    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

3. **Would you like to collaborate on our site?**
    As mentioned in the _previous question_, I am in a time crunch, so I would have to pass on such opportunities.

**Connect to me on**

-   [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose-429a601a0)
-   [Portfolio](https://tapajyoti-bose.vercel.app)
-   [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)
-   [GitHub](https://github.com/ruppysuppy)
-   [Instagram](https://www.instagram.com/tapajyotib/)