TypeScript import aliases

Sun Dec 31

Are you tired of having code that looks like this?

import Navigation from "../../../anotherFolderOfComponents/Navigation.astro";
import Hamburger from "../../../anotherFolderOfComponents/Hamburger.astro";
import ThemeIcon from "../../../anotherFolderOfComponents/ThemeIcon.astro";

Wouldn’t you much prefer code that looks like this?

import Navigation from "@components/Navigation.astro";
import Hamburger from "@components/Hamburger.astro";
import ThemeIcon from "@components/ThemeIcon.astro";

Well do I have a solution for you! We can use tsconfig.json’s compilerOptions flags to create aliased imports!

  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@assets/*": [
        "src/assets/*"
      ],
      "@pages/*": [
        "src/pages/*"
      ],
      "@components/*": [
        "src/components/*"
      ],
      "@layouts/*": [
        "src/layouts/*"
      ],
      "@images/*": [
        "src/assets/images/*"
      ],
      "@posts/*": [
        "src/content/posts/*"
      ],
    }
  }

Much better!