Typescript Paths

I really hate having to type '../' over and over to try and remember how deep my typescript file in in the directory structure, just to include a constants file or something from the utils directory. Now that I have discovered TypeScript 'paths' I no longer need to!

tsconfig.json changes

To set this up, edit the tsconfig.json file such that:

{
  "compilerOptions": {
  ...
  "baseUrl": "/src",
  "paths": {
    "#components/*": "components/*",
    "#utils/*": "utils/*"
  }
  ...
  }
  ...
}

Path Name

So, I like to use a '#' character to distinguish between node module imports and developer (project) imports. I have seen other examples where developers use an "@/components" root path.

Usage

With this done, typescript files will be able to make use of these 'pointers' in the import statements; for example:

import { Button } from '../../../components/Button';

Can be rewritten as:

import { Button } from '#components/Button';

Note: I had to restart my Dev server to pick up the changes.

Reference

typescriptlang.org/docs/handbook/module-res..