chevron-left chevron-right

How to configure custom absolute imports in your TypeScript project?

When developing apps using modern syntax following ES6+ standards you can get to the point that your files and directories structure is deeply nested. This makes importing code a little bit complicated.

The folders structure might look like this:

Sample nested folders structure in NextJS app

It's the sample folder structure in my NextJS app. I'm not going to talk much about NextJS, but it's a React-based framework for building server-side-rendered apps.

Usually when developers have such a structure and want to import some components from components directory located in the project root directory, they type something like this:

import { Header } from '../../../components/Header';

There's a lot of going back in the structure with relative path notation - ../, in order to import a Header component into the [id].tsx file.

Changing relative imports into absolute imports

Supposing that you're using Webpack in your TypeScript project you can convert relative imports into absolute imports with ease. So instead of typing:

import { Header } from '../../../components/Header';

You'll type your code the following way at the end:

import { Header } from '@components/Header';

It's much easier! So how can you do it in your project? There are 2 steps required.

Configuring tsconfig.json

Firstly we have to inform TypeScript that we have defined our custom absolute paths, so type hinting will work without any issues.

{
  "compilerOptions": {
  "paths": {
    "@components/*": ["components/*"],
    "@layouts/*": ["layouts/*"]
  },
  ...
}

Configuring Webpack resolver

The next step is to configure Webpack resolver to understand the new custom absolute paths. Here's the piece of code you need to add in webpack.config.js file, in order to make it working:

module.export = {
  resolve: {
    alias: {
      '@components': '/components',
      '@layouts': '/layouts'
    },
    extensions: ['.ts', '.tsx', '.js', '.json'],
  }
}

And that's it. Now you should be able to use your custom absolute paths and forget about nested relative paths hell!

Summary

I hope you'll find this article useful. Configuring custom absolute paths makes developers' life easier, because from now on they don't have remember how deeply nested components is. They just import it the similar way the npm packages are used, like React or Redux. Use advices from this post in your projects and forget about mistyping nested relative paths in projects, making your codebase less error-prone.