Ugly imports in TypeScript (Solved)
I hope you are doing well.
When I review code from TypeScript projects, I often see ugly and long imports, like so:
typescriptimport LoadingButton from "../../../../../components/LoadingButton"
Depending on how deep your folder structure is, those kinds of imports can quickly get out of hand.
There must be a better way to import in TypeScript.
Of course, there is, using alias paths.
Using alias paths, you can map an alias to a path, resulting in short and convenient import statements.
Here is how to make it work:
- Set the baseUrl option to "." in your tsconfig.json file.
- Add your aliases to your tsconfig.json file.
That's it! You can now import using aliases from anywhere in your project tree!
Here is how the import looks now:
typescriptimport LoadingButton from "@components/LoadingButton"
Cool right?
Articles
Here is the latest article on the blog:
Thank you for reading.
See you next week!
Tim M.
Page content