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';
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 baseurl from "./" to "src".
"compilerOptions": {
"baseUrl": "src",
....
Define shortcut for each area for example components or state, page etc.
"paths": {
"@app/*": ["app/*"],
"@pages/*": ["app/pages/*"],
"@components/*": ["app/components/*"],
"@state/*": ["state/*"]
},
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.
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)
hi,
After the file is compiled, I get the Cannot find package error. what is the problem!
To make easy help you, please paste the error with screenshot.