なんじゃくにっき

プログラミングの話題中心。

Astroを使って静的サイトを作ってGithub Pagesにデプロイするまで

概要

昨日、静的サイトジェネレーター比較なんて記事を書きましたが、そこで挙げたAstroの使い方です。

基本チュートリアルに従って行けば良く、変更しないといけない箇所はあまりありませんが。

インストール

公式ドキュメントに従います。

Astroを自動CLIでインストール | Docs

※事前にnode.jsのインストールが必要です

npm create astro@latest

と打てば作成するディレクトリを聞いてくるのであとはyesを選択しておけば終わるでしょう。簡単。

Github Pageにインストールする設定

AstroサイトをGitHub Pagesにデプロイする | Docs

astro.config.mjsを編集してsiteとbaseを設定します。

import { defineConfig } from 'astro/config'

export default defineConfig({
  site: 'https://astronaut.github.io',
  base: '/my-repo',
})

siteはastroがサイトマップを正しく生成するのに必要、

baseはGithub Pages内でのリンクを正しく生成するのに必要。

また

.github/workflows/deploy.ymlに公式サイトからファイルをコピペします。

ここまででローカルで

npm run dev

とすると http://localhost:4321/my-repo で起動、

githubのmainブランチpushするとGithub Actionsが起動してGithub Pagesにデプロイされるでしょう。

ここまでで最低限動くのであとは自分の使いたいライブラリを入れていく。

tailwind

@astrojs/tailwind | Docs

npx astro add tailwind

で使えるようになります。

React

npx astro add react

で使えるようになります。

src/components以下のディレクトリにjsxないしtsxでReact Componentを作って

astroファイルのコンポーネントスクリプト部分でimportしたらコンポーネントテンプレート部分で使えるようになります。

---
import Layout from '../layouts/Layout.astro';
import Card from '../components/Card.tsx';
---

<Layout title="ホーム">
  <Card />
</Layout>

他のライブラリ

ライブラリを追加したいときはnpm installして使うのはいつものやつですが、

[vite] Named export 'QRCodeSVG' not found. The requested module 'qrcode.react' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'qrcode.react';
const {QRCodeSVG} = pkg;

みたいなエラーが出ることがあります。

これはviteのnoExternal設定を追加すると解決します。

astro.config.mjs

export default defineConfig({
  site: 'https://nanjakkun.github.io',
  base: '/hyattoku',
  integrations: [react(), tailwind()],
  vite: {
    ssr: {
      noExternal: ["qrcode.react"],
    },
  },
});