エンジニアを目指す初学者に向けて、わかりやすく解説したブログです。

AstroでGitHub Pagesにサイトを公開するときの注意点

ここでは、Astroで作成した静的サイトをGitHub Pagesで公開するときの注意点を紹介します。

ポイント

  1. GitHub Pagesの公開URLは https://アカウント名.github.io/リポジトリ名/であり、リポジトリ名がパスになっていること
  2. GitHub Pagesはデフォルトで jekyllを使って公開されること

1. ビルドしたものを docsに吐き出すようにする

Astroはデフォルトで dist/ディレクトリに成果物を作成する。

GitHub Pagesがサイトを公開できるのは /もしくは /docsに入っているリソースに限られるため、
npm run buildしたときに出力されるディレクトリを変更する必要がある。

// astro.config.mjs
import { defineConfig } from 'astro/config'
import tailwindcss from '@tailwindcss/vite'
import icon from 'astro-icon';

// https://astro.build/config
export default defineConfig({
  outDir: './docs', // これを設定する
  vite: {
    plugins: [tailwindcss()],
  },

  integrations: [icon()],
});

参考:Icon in a page linkGitHub Pages サイトを作成する - GitHub ドキュメント

2. ベースとなるURLとパスをconfigで設定する

一般的なサイトはドメイン直下に配置することが多いため、何も設定しないと以下のようなパス解決になる。

<link rel="stylesheet" href="/_astro/index.DYmQrXqt.css">

この場合、誤ったパスを参照してしまうためNGである。

  • 誤: https://アカウント名.github.io/_astro/index.DYmQrXqt.css
  • 正: https://アカウント名.github.io/リポジトリ名/_astro/index.DYmQrXqt.css

そのため、 astro.config.mjsなどで sitebaseの指定を行う必要がある。

// astro.config.mjs
import { defineConfig } from 'astro/config';
import tailwindcss from '@tailwindcss/vite';
import icon from 'astro-icon';

// https://astro.build/config
export default defineConfig({
  // GitHub Pages公開のため
  site: 'https://アカウント名.github.io',  // これと
  base: '/リポジトリ名',                   // これを設定する
  outDir: './docs',
  vite: {
    plugins: [tailwindcss()],
  },

  integrations: [icon()],
});

3. _から始まるディレクトリを無視されないようにする

ソースブランチからサイトを公開する場合、GitHub Pagesではデフォルトでjekyllを使ってサイトをビルドするようになっている。

このとき、 _から始まるファイルやディレクトリは無視されてしまう。

Astroはビルド済みの成果物なので、この機能を無効化するために .nojekyllファイルの配置が必要である。

Astroの場合は、 public/ディレクトリに配置しておけば、 npm run buildしたときに自動的に docs/に出力される。

参考:Icon in a page linkGitHub Pages サイトを作成する - GitHub Enterprise Server 3.18 Docs

4. faviconなどのパスも解決しておく

hrefで指定している静的ファイルのパスも、おそらくパスが誤っている状態になっているので修正が必要。

<link rel="icon" type="image/svg+xml" href={`${import.meta.env.BASE_URL}/favicon.svg`} />

import.meta.env.BASE_URLには/リポジトリ名が入る。