DEV Community

Cover image for Use fancy imports with path mapping in tsconfig
Dany Paredes
Dany Paredes

Posted on

 

Use fancy imports with path mapping in tsconfig

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

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

To fancy paths like:

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

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 baseurl from "./" to "src".

"compilerOptions": {
    "baseUrl": "src",
....
Enter fullscreen mode Exit fullscreen mode

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

 "paths": {
      "@app/*": ["app/*"],
      "@pages/*": ["app/pages/*"],
      "@components/*": ["app/components/*"],
      "@state/*": ["state/*"]
 },
Enter fullscreen mode Exit fullscreen mode

Done! Then 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 automatic.

Before and after.

Differences between code

That's it!

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!

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!