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.

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`

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, the first one is ❶ baseUrl which refer 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.

The other property will be ❷ 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, here are some resources that might help:

🔗 how modules are resolved in webpack

🔗 babel pluagin module resolver


I hope you found this quick article useful, if so, share it on social networks 😊.

Tot ziens 👋

Discuss on Twitter
Medhat Dawoud is a JavaScript Engineer with over a decade of software engineering experience. He is enjoying writing blog posts and making technical videos on his channel on YouTube. He also has published a course called Redux Recipes early in Feb 2019. He lives with his wife and a little daughter in Amsterdam.