Organising Imports With Typescript Path Mapping.

Organising Imports With Typescript Path Mapping.

I read about this cool feature a while back, as I didn’t like the way the import paths looked especially when it’s the first thing you tend to read when opening a typescript file.
I have just had a chance to give it a go, so here is what I have found so far, Typescript has a cool feature which allows you to set an alias path mapping for paths. Imports look much cleaner this way and because they reference the mapped path, they can be easily changed in just one place, and not every typescript file they are used in. Restructuring project file trees is now a lot easier with this feature.

This is how imports generally look, and they get larger and larger as the project increases in size, all referencing different paths in the project tree.

import { LanguageService } from '../../../services/language.service';

Now let’s change our tsconfig.json and make use of path mapping.
We add a paths key, to our compiler options with the services alias mapping to our services folder.

  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@services/*": [

Now we can use the following import in our typescript file, looks cleaner doesn’t it?

import { LanguageService } from '@services/language.service';

This is a great way to start off a new project, it’s more readable and is easier to maintain. VS code also detects this path mapping, and suggests it should import the path using the mapping provided.