Day23 - Astro Series: Aliases

A nice gradient background with a title: "Path Aliases"

Introduction

When writing import paths you’ll find that relative paths are tedious and hard to maintain. You can solve this by adding path aliases.

Why Path Aliases (Aliases)

As a site grows more complex, using relative paths requires a lot of effort to read and write. For example, in the file src/pages/about/company.astro you might need to import the Button.astro component located in src/components/global/. Writing the path requires understanding the relationship between the two files, and if either moves the path must be updated.

---
<!-- 又長又難寫! -->
import Button from '../../components/global/Button.astro'
---

Solution

You can set project “path aliases” in tsconfig.json or jsconfig.json:

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

Then you only need to use the alias in your imports without worrying about the file relationships:

---
import Button from '@components/global/Button.astro
---

Conclusion

Astro’s path alias setup is actually the same as Vite’s.

Further reading