👾
Astro に Path alias を設定する
前回 Astro x TypeScript + React のプロジェクトに Prettier, ESLint を導入したので、
パスエイリアスも使えるようにして開発体験を良くしていき
環境
- astro@5.7.5
- typescript@5.8.3
- react@19.1.0
👾 Astro x Path alias の設定
Astro は tsconfig にパスエイリアスを設定すれば、パスエイリアスとして扱われる
tsconfig.json に path alias を設定
tsconfig.json
{
"extends": "astro/tsconfigs/strict",
"include": [
".astro/types.d.ts",
"**/*"
],
// ...
"compilerOptions": {
"baseUrl": ".",
+ "paths": {
+ "@/*": ["./src/*"],
+ "~/*": ["./public/*"]
+ }
}
}
Editor (VSCode, Cursor) でも補完が効くようにする
.vscode/settings.json
{
//...
+ "path-autocomplete.pathMappings": {
+ "@": "${folder}/src",
+ "~": "${folder}/public"
+ }
}
内部的に vita が使われている様なので vite-tsconfig-paths で明示的に tsconfig のパスエイリアスを使っていることを表現できる (設定の必要はなさそう)
Astro builds on top of Vite, and supports both Vite and Rollup plugins.
https://docs.astro.build/en/recipes/add-yaml-support/
$ npm i -D vite-tsconfig-paths
astro.config.mjs
+ // @ts-check
import react from '@astrojs/react';
import { defineConfig } from 'astro/config';
import tsconfigPaths from 'vite-tsconfig-paths';
// https://astro.build/config
export default defineConfig({
output: 'static',
vite: {
+ plugins: [tsconfigPaths()],
},
integrations: [react()],
});
Discussion