AY

Path Aliasing With TypeScript

JavaScript (TypeScript)
React

Alex | Last updated: October 1, 2023

This is one of those things I can’t believe and am upset I didn’t learn sooner.

I’ve worked on many projects in React where component files start like this:

// Some Component.tsx file
import Component1 from "../../../path/to/Component1";
import Component2 from "../../../../path/to/Component2";
import Component3 from "../path/to/Component3";
import Component4 from "./path/to/Domponent4";

And this is freaking ugly. And this relative path stuff gets really nasty when we want to change our directory structure—which is fairly common for early stage projects.

VSCode offers a nice, user-friendly prompt whenever we move files around:

A kind VSCode prompt for updating imports
A kind VSCode prompt for updating imports. Hero.

But I recently learned about aliasing, whereby we could change our tsconfig.json (or jsconfig.json if you’re using plain js/jsx) configuration file to include the following:

// tsconfig.json
"compilerOptions": {
  //... some options
  "baseUrl": ".",
  "paths": {
    "@components/*": ["src/components/*"],
  }
  /// some more options
}

Entries in paths create a map to help TypeScript look up file locations relative to the provided baseUrl (if no baseUrl is set, TypeScript will search for files by their paths relative to the tsconfig.json file location, but I’d recommend just setting that baseUrl parameter to make everyone’s lives easier).

This configuration helps clean up our ugly import statements to look like this:

// Some Component.tsx file
import Component1 from "@components/path/to/Component1";
import Component2 from "@components/path/to/Component2";
import Component3 from "@components/path/to/Component3";
import Component4 from "@components/path/to/Domponent4";

How lovely.

We still need to worry about changes to directory structure relative to the provided path roots, as well as changes to file names, but this helps remove all the nastiness that comes with importing using relative paths.

This trick also works for other folders, e.g.:

// tsconfig.json
"compilerOptions": {
  //... some options
  "baseUrl": ".",
  "paths": {
    "@components/*": ["src/components/*"],
    "@assets/*": ["src/assets/*"],
    "@styles/*": ["src/styles/*"],
    "@lib/*": ["src/lib/*"]
  }
  /// some more options
}

If we wanted to reduce repetition (remove src from each alias declaration), we could do something like this:

// tsconfig.json
"compilerOptions": {
  //... some options
  "baseUrl": "./src",
  "paths": {
    "@components/*": ["./components/*"],
    "@assets/*": ["./assets/*"],
    "@styles/*": ["./styles/*"],
    "@lib/*": ["./lib/*"]
  }
  /// some more options
}

or even:

// tsconfig.json
"compilerOptions": {
  //... some options
  "baseUrl": "./src",
  "paths": {
     "@/*": ["./*"]
  }
  /// some more options
}

Nice.