Use fancy imports with path mapping in tsconfig

Use fancy imports with path mapping in tsconfig

In typescript or Angular apps, we can avoid having ugly paths like the following example.

import { BookMark } from 'src/app/models/bookmark';
import { BookmarksState } from './../../../state/bookmarks.state';
import { GetBookMark } from './../../../state/bookmarks.actions';

To fancy paths like:

import { BookMark } from '@app/models/bookmark';
import { BookmarksState } from '@state/bookmarks.state';
import { GetBookMark } from '@state/bookmarks.actions';

##How? All magic is part of the TypeScript compiler. It supports declaration mappings using "paths" property in tsconfig.json files.

First, define your base path; if you are in angular applications, into the compiler options, change the base URL from "./" to "src".

"compilerOptions": {
    "baseUrl": "src",
....

Define shortcuts for each area, for example, components or state, page, etc.

 "paths": {
      "@app/*": ["app/*"],
      "@pages/*": ["app/pages/*"],
      "@components/*": ["app/components/*"],
      "@state/*": ["state/*"]
 },

Done, change your code in components or files, and vscode will detect the new paths from tsconfig.

Sometimes, you need to reopen it to detect new paths automatically.

Before and after.

Differences between code

Final

Hopefully, that will give you a bit of help to write clean paths in Typescript or Angular apps. If you enjoyed this post, share it!