Astro の import statement で alias を使ってパス指定を簡単にする

Created on

Astro では、alias を使って import statements でのパス指定を簡単にすることができる。 import Button from '../../components/Button.astro'; のように相対パスで書いた場合、ファイルの移動があった場合にこの import statement も書き換える必要があるが、alias を使うことで import Button from '@components/Button.astro'; のような書き方が使えるので逐一パスを書き換える必要がなくなる。

この機能を使うには tsconfig.jsoncompilerOptions.paths を次のようにする。

tsconfig.json
{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"],
  "compilerOptions": {
    "paths": {
      "@components/*": ["./src/components/*"]
    }
  }
}

参考