astroでプロジェクトを新規作成すると、デフォルトでは相対パスで書かれている。
これを絶対パスで書きたい。スッキリするので。
設定
下記2ファイルにパスの設定を追加する。
解説は後述。
astro.config.mjs
import { defineConfig } from "astro/config";
import mdx from "@astrojs/mdx";
import sitemap from "@astrojs/sitemap";
import { fileURLToPath } from "node:url";
import path, { dirname } from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export default defineConfig({
site: "https://example.com",
integrations: [mdx(), sitemap()],
vite: {
resolve: {
alias: {
"@/": `${path.resolve(__dirname, "src")}/`,
},
},
},
});
参考
tsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
結果
index.astro
// 設定前
import Component from '../../../src/components/MyComponent.astro';
// 設定後
import Component from '@/components/MyComponent.astro';
解説
ディレクトリのパスを取得する
astro.config.mjs
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
- import.meta.url で現在のモジュールファイルのURLを取得する
- fileToPath() でfile://URL を通常のファイルパスに変換する
(例:C:/Users/username/project/blog/src/pages/index.astro) - dirname() でファイルパスからディレクトリ部分を抽出
(例:src/pages/index.astro)
※astroのコードフェンス(上部の---で囲まれた部分)にconsole.log()を記載した場合、ブラウザのコンソールではなく、Astro CLIを実行しているターミナル(vscodeのターミナルなど)にログが表示される。
astroの設定にパスを明示する
astro.config.mjs
"@/": `${path.resolve(__dirname, "src")}/`,
- "@/" のパスは、srcディレクトリを表すことを明示する
TypeScriptにエイリアスを認識させる
tsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
- "@/" から続くパスは、 "./src/" と同じことをTypeScriptが認識できるようにする
※解説部分はClaude4 Sonnetの力を借りました。