Hey! in this short and quick note Iโd recommend to everyone to use in the current or in the future typescript projects you are going to work on, I would say itโs not a new tip and most of you might know it already but itโs important in my opinion and enhance the readability of your code for other people specially new comers to the team.
Problem
Have you ever seen this look in your projects imports ../../../../../
or even sometimes more ../../../../../../../../../
I believe you did, since most people prefer the auto-import in their editors like vscode or webstorm or anyother one, I would give you a shortcut to convert your import statement for instance from this ๐:
import Test from `../../../../../../../src/app/components/test`
to this elegant one ๐ even with auto-import:
import Test from `@components/test`
Solution
The solution is very easy, just open your tsconfig.json
in your application and add 2 more properties in case you didโt find them already
First: baseUrl
Which refers to the directory that you need your application to consider as a root directry or a base url, itโs value might be src
folder or app
folder as you want.
Second: paths
Which holds an object of shortcuts for the TypeScript transpiler and editor checkers, in this case you want it to be kind of
"@components/*": ["./app/components/*"]
this means that any import starts with @components
please search inside the corresponding folder or folders as you can see you can add more than one alias into the same key, just write more values to the array.
So the final example after adding them, the tsconfig.json
file should be as follow:
...
"baseUrl":"src",
"paths":{
"@components/*":["src/app/components/*"]
}
Thatโs it for the TypeScript, in fact Iโm adding the @
sympol here just to remind myself while reading the code that this path is an alias to the original internal file in my application but you can name it whatever works for you.
In case you are using babel or webpack there are some similar configurations for both of them you can make as well to make sure that the trancpiler is working fine with the new paths.
Resources that might help:
๐ how modules are resolved in webpack ๐
๐ babel pluagin module resolver ๐
Tot ziens ๐