Avoid relative import paths in TypeScript
If you have been working with TypeScript lately, you might have used relative paths to import modules or files. So, for instance, let’s say if I want to import a module that is two directories up from the current file location, I would need to import it like so.
import Order from '../../components/order';
Now, in my opinion, this way of importing things is not easy to comprehend and you’ve to keep track of the level of the directory you’re currently in, which is not friendly at all and kind of sucks.
The fix
To fix this, all you need is to set a compilerOptions.baseUrl
config in your project’s tsconfig.json
file.
So, if we want to make the src
folder (which sits at the root of the project) as the base of every import, we can set it like so.
{
"compilerOptions": {
"baseUrl": "./src"
}
}
And that’s it! Now, you won’t need to write those pesky relative import paths anymore.
The previous example would be simplified to this after setting this configuration.
import Order from 'components/order';
This will get resolved to ./src/components/order
.
👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I do and want me to continue doing the same, I'd like you consider leaving a tip. I'd highly appreciate that. Cheers!