Paths and baseUrl in tsconfig.json

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

shortcut

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.

Important Note: after adding such settings to the tsconfig file make sure to restart your editor to take effect of these changes.

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:

Tot ziens 👋

SHARE