Skip to main content

Command Palette

Search for a command to run...

Use aliases for your imports

Avoid mistakes with import aliases

Updated
1 min read
Use aliases for your imports
R

Front-end software engineer and I specialise in Angular🤖. I've been working with it since Angular JS and I like to keep up with new technologies. I love to write about Angular, TypeScript, JavaScript and more 📰. My hobbies are travelling around Southeast Asia ✈️, cars and technology.

In TypeScript projects, especially in Angular, it's easy to have too many files and too many imports in our components. This leads to confusion and errors when importing. In this post we have a quick guide to avoid this.

We've all seen this type of import in our files:

import { Something } from '../../../../../../../something.ts';

You can work around this by using aliases in the tsconfig.json attribute via paths:

// tsconfig.json
{
  "compilerOptions": {
    ...
    "paths": {
      "@components/*": ["src/app/components/*"],
      "@routes/*": ["src/app/routes/*"],
      "@shared/*": ["src/app/shared/*"],       
    }
  }
}

You can then use these aliases to import your resources:

import { ButtonComponent, CardComponent } from '@components';
import { formatText } from '@shared/utils/formatting';
import { converting } from '@shared/utils/converting';

Conclusion

You should do this for several reasons:

  • It is much easier to read than relative paths.

  • This is useful for refactoring: if your code changes location, the import stays the same.

  • IDEs can import directly from aliases