Problem
In the recent project, we’ve mentioned about one question:
why do we do our imports as relative paths rather than absolute paths? It’s not easy to figure out what’s the correct path.
We then start discussing what the pros and cons are for using an absolute path or relative path. To my best knowledge, I always voted for the relative path, cause that won’t cause a problem when we try to deploy the service into different file paths. But the con is that we need first to figure out what’s the correct import path. But using an absolute import path is the contrary.
In the project, you might sometimes find this:
1 | import { Service1 } from '../../../../core/services/service1'; |
I admit it’s tough to get understanding what the real path for a service is.
Solution
So, we are trying to find a better solution than this way. According to the TypeScript handbook, it seems we can use baseUrl to solve our problem. Here is an example:
tsconfig.json
1 | { |
You can set up the baseUrl
and paths
these two properties. It would look like the following code:
1 | { |
after setting up this in your project, you can use it in this way:
1 | import { Service1 } from '@core/services/service1.ts'; |
That makes life lots more comfortable.
Happy coding, enjoy.