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 want to use paths-aliases from your tsconfig.json
{
"compilerOptions": {
"paths": {
"@helper": ["src/shared/helper.ts"]
}
}
}
and import them in the astro.config.ts, you will get one of this errors:
[vite] Pre-transform error: Failed to load url @helper (resolved id: @helper) in {path}/astro.config.ts. Does the file exist?
Cannot find module '@helper' imported from '{path}/astro.config.ts'
As you can see in this Pull-Request from Astro, its a known bug, but it won't get fixed. So you have to fix it on your own.
After this there is a file at `patches/astro+{version}.patch` with content like this:
diff --git a/node_modules/astro/dist/core/config/vite-load.js b/node_modules/astro/dist/core/config/vite-load.js
index 949a541..ec8b7a7 100644
--- a/node_modules/astro/dist/core/config/vite-load.js
+++ b/node_modules/astro/dist/core/config/vite-load.js
@@ -1,8 +1,11 @@
import { pathToFileURL } from "node:url";
import { createServer } from "vite";
+import configAliasVitePlugin from '../../vite-plugin-config-alias/index.js';
import loadFallbackPlugin from "../../vite-plugin-load-fallback/index.js";
import { debug } from "../logger/core.js";
+import { loadTSConfig } from './tsconfig.js';
async function createViteServer(root, fs) {
+ const tsConfig = await loadTSConfig(root);
const viteServer = await createServer({
configFile: false,
server: { middlewareMode: true, hmr: false, watch: null, ws: false },
@@ -23,7 +26,12 @@ async function createViteServer(root, fs) {
"@astrojs/db"
]
},
- plugins: [loadFallbackPlugin({ fs, root: pathToFileURL(root) })]
+ plugins: [
+ configAliasVitePlugin({
+ settings: { tsConfig: tsConfig.tsconfig, tsConfigPath: tsConfig.tsconfigFile },
+ }),
+ loadFallbackPlugin({ fs, root: pathToFileURL(root) }),
+ ]
});
return viteServer;
}
Now just restart astro and it should work.