ABSOLUTE
VS. RELATIVE
PATHS/LINKS
When importing modules
in typescript
they are usually separated in two:
- Importing libraries modules, which is quite nice, since we use only the name and they are resolved from node_modules folder
- Importing modules from our own application
When importing modules from our own application there are two way of addressing
Relative Paths
e.g: import { environment } from '../../../../environments/environment';
Absolute Paths
e.g: import { environment } from 'src/environments/environment';
There are full of examples that use relative paths
but it goes quickly wrong when the file we need is several levels up or down. Then we get something like:
import { foo } from ‘../../../../bar’;
Since TypeScript 2.0
, we have an awesome compiler setting called baseUrl
, and we can configure it in the tsconfig.json
file like:
{
"compilerOptions": {
"baseUrl": "./src"
}
}
By this way you can use absolute path like this:
import { foo } from ‘app/bar’
For more information about absolute
paths check this quick guide: Use absolute paths for module imports
In addition, there is similar discussion here:
Avoiding relative paths in Angular CLI
& check both thees answers of this question:
https://stackoverflow.com/a/41460972/4185370
https://stackoverflow.com/a/43319965/4185370
So, as a conclusion the first one absolute
paths are better, but with the right configuration through tsconfig.json
.