Import Aliases in an Astro project

Astro is a great tool for building blogs, landing pages or any other frontend application really. When working with Astro you’ll typically end up importing components from another directory and this can get really tedious having to figure out how many directories you need to go up or down to import the component. Luckily, Astro supports import aliases and this is how you set them up.

So you’ve got an Astro project with a file structure that looks something like this:

|
|-- src
|   |-- pages
|       |-- index.astro
|   |-- components
|       |-- Nav.astro
|-- astro.config.mjs
|-- tsconfig.json

We want to import our Nav.astro component into our index.astro page. Currently the import path would be ../components/Nav.astro. But we can make it much more elegant.

In our tsconfig.json we will add our aliases:

"compilerOptions": {
    "baseUrl": ".",
    "paths": {
        "@/components/*": ["src/components/*.astro"],
    },
},

We need to make sure we set the baseUrl to . so that we’re in the root of our project. Then we add our alias: @/components/*, which directs to src/components/*.astro. Now in our index.astro we can import the Nav component like so:

---
import Nav from "@/components/Nav";
---

The beauty of aliases like this is that we don’t need to use the file extension anymore.

I hope this short tutorial will help you become super productive in your Astro projects. More Astro on the way.

Sponsored by Vizalo

Protypo is sponsored by Vizalo - powerful yet affordable servers with locations in Europe and North America.