Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?