Code for breakfast.

Absolute path imports in TypeScript

Ever gone hunting for directories? Adding and removing ../ to your module import paths until your bundler and IDE stop throwing errors?

import CoolComponent from '../../../subdir/CoolComponent';

If you've made the switch to TypeScript, you're in luck! The compiler ships with support for absolute paths in import statements.

With a small tweak to your tsconfig.json file, you can make all imports honor a base URL - an abitrary directory that acts as a root path for any imports in your project. For example, if you set your base URL to the src directory at the root of your project, you could rewrite the above snippet to like like this -

import CoolComponent from 'components/subdir/CoolComponent';

All that's required is specifying compilerOptions.baseUrl in tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}

Tip: If you're using NextJS or don't have a top-level source directory, you can set the base to your project's root directory with "baseUrl": ".".