First tech post, yay!
Writing code in Angular using Visual Studio Code is a real pleasure: syntax highlighting, autocompletion, Git integration, auto imports, and more. From time to time, though, you find some odd routes in your imports that can be improved using the tsconfig.json file.
Let’s imagine you want to import a component that is deep in the folder structure. You will end up with something like this:
@import "../../../../../modules/shared/components/date-time/date-time.component";
If you use an absolute path the result is slightly better:
@import "src/app/modules/shared/components/date-time/date-time.component"
TypeScript provides a solution. Inside the tsconfig.json file, you have a paths option that lets you declare path aliases and shorten imports significantly. The route provided inside the path is relative to the baseUrl configuration in the same file.
{
"compilerOptions": {
..
"baseUrl": "src",
"paths": [
"@shared-module/*": [
"app/modules/shared/*"
],
]
}
}
From now on, you can import files from shared modules this way:
@import "@shared-module/components/date-time/date-time.component"
Final note: this feature depends on your build tool, so you may need to modify its configuration. In webpack 2, for example, you will need to add the new path to the resolve alias array in webpack.config.js:
alias: {
'@shared-module': gpath.resolve(\_\_dirname, `../src/app/modules/shared`),
}