How to use Typescript paths-aliases in astro.config.ts
Astro is missing a important vite-plugin for Typescript. I show you, how to add this plugin correctly.
If you create an Astro project with TypeScript and add path aliases in `tsconfig.ts` like this:
{
"compilerOptions": {
"paths": {
"@helper": ["src/shared/helper.ts"]
}
}
}
Then you may notice that a crucial Vite plugin is missing to use type aliases correctly. The absence of this configuration often leads to issues with path resolution and causes error messages like:
[vite] Pre-transform error: Failed to load url @helper (resolved id: @helper) in {path}/astro.config.ts. Does the file exist?
[vite] Error when evaluating SSR module {path}/astro.config.ts: failed to import "@helper"
Cannot find module '@helper' imported from '{path}/astro.config.ts'
[astro] Unable to load your Astro config
As you can see in this Pull-Request from Astro, this is a known bug that won't be fixed. So you'll need to address it yourself. In this article, I'll show you step-by-step how to properly integrate the necessary plugin for TypeScript paths and configure it in your `tsconfig.json` and `astro.config.ts`. This way, you can use alias paths efficiently in your project without error messages.
Now just restart astro and it should work.