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 (2)

Collapse
 
saeedjhn profile image
saeedjhn

hi,

After the file is compiled, I get the Cannot find package error. what is the problem!

Collapse
 
danywalls profile image
Dany Paredes

To make easy help you, please paste the error with screenshot.