[Astro] インストールとプロジェクト構成

2026-03-25 hit count image

Astroをインストールしてブログプロジェクトを構成する方法を共有します。astro.config.mjs設定、ディレクトリ構造、SCSS設定、ビルドスクリプトなどを扱います。

astro

概要

前回の記事JekyllからAstroへマイグレーションした理由JekyllからAstroに移行することになった背景を共有しました。今回の記事では、実際にAstroをインストールしてブログプロジェクトを構成する方法をステップバイステップで説明します。

事前準備

AstroNode.jsベースなので、まずNode.jsがインストールされている必要があります。

Node.jsのインストール

Node.js公式サイトからLTSバージョンをインストールします。nvm(Node Version Manager)を使用すると複数のバージョンを簡単に管理できます。

# nvmでNode.jsをインストール
nvm install --lts
nvm use --lts

# バージョン確認
node -v
npm -v

プロジェクトルートに.nvmrcファイルを作っておくと、チームメンバーとNode.jsのバージョンを統一できます。

Astroプロジェクトの作成

Astroは公式CLIツールでプロジェクトを素早く作成できます。

npm create astro@latest

CLIの案内に従ってプロジェクト名、テンプレートなどを選択します。ブログの構造を最初から自分で設計するとプロジェクトへの理解度が高まるため、空のプロジェクト(Empty)から始めることをお勧めします。

# プロジェクト作成後に移動
cd my-blog

# 依存関係のインストール
npm install

# 開発サーバーの起動
npm run dev

開発サーバーが起動するとhttp://localhost:4321でサイトを確認できます。ViteベースのHMRのおかげでファイルを修正するとブラウザに即座に反映されます。

プロジェクトディレクトリ構造

このブログのプロジェクトディレクトリ構造は以下の通りです。

/
├── public/                  # 静的ファイル(画像、robots.txtなど)
│   ├── assets/
│   │   └── images/
│   ├── robots.txt
│   ├── ads.txt
│   ├── CNAME
│   └── .nojekyll
├── src/
│   ├── components/          # 再利用可能なAstroコンポーネント
│   │   ├── Head.astro
│   │   ├── Navbar.astro
│   │   ├── Footer.astro
│   │   ├── Breadcrumbs.astro
│   │   ├── Comments.astro
│   │   ├── SearchBar.astro
│   │   ├── SearchPage.astro
│   │   ├── Pagination.astro
│   │   ├── CategoryCard.astro
│   │   ├── PostCard.astro
│   │   └── ads/             # 広告コンポーネント
│   ├── content/             # ブログポスト(Content Collections)
│   │   ├── astro/
│   │   ├── react/
│   │   ├── jekyll/
│   │   └── ...
│   ├── data/                # 静的データ
│   │   └── categories.ts
│   ├── i18n/                # 多言語翻訳
│   │   └── translations.ts
│   ├── layouts/             # レイアウトテンプレート
│   │   ├── BaseLayout.astro
│   │   └── PostLayout.astro
│   ├── pages/               # ルートページ
│   │   ├── [...path].astro  # 日本語(デフォルト)
│   │   ├── ko/              # 韓国語
│   │   └── en/              # 英語
│   ├── plugins/             # カスタムrehypeプラグイン
│   │   ├── rehype-picture.mjs
│   │   └── rehype-in-feed-ads.mjs
│   └── styles/              # グローバルスタイル
│       └── global.scss
├── scripts/                 # ビルド/デプロイスクリプト
│   └── share.mjs
├── astro.config.mjs         # Astro設定
├── package.json
└── tsconfig.json

主要ディレクトリの説明

主要ディレクトリをもう少し詳しく見ると以下の通りです。

ディレクトリ役割
public/ビルド時にそのままコピーされる静的ファイル。画像、フォント、検証ファイルなど
src/components/再利用可能な.astroコンポーネント。Head、Navbar、Footerなど
src/content/Content Collectionsで管理されるマークダウンブログポスト
src/data/カテゴリ定義などの静的データ
src/i18n/多言語翻訳およびヘルパー関数
src/layouts/ページレイアウトテンプレート
src/pages/ファイルベースルーティング。ディレクトリ構造がそのままURL構造
src/plugins/カスタムrehype/remarkマークダウン処理プラグイン
src/styles/グローバルSCSSスタイル

astro.config.mjs設定

Astroのコア設定ファイルです。このブログで使用している実際の設定を見ていきましょう。

// @ts-check
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
import rehypeExternalLinks from 'rehype-external-links';
import rehypeCallouts from 'rehype-callouts';
import rehypeInFeedAds from './src/plugins/rehype-in-feed-ads.mjs';
import rehypePicture from './src/plugins/rehype-picture.mjs';

export default defineConfig({
  site: 'https://deku.posstree.com',
  output: 'static',
  build: {
    inlineStylesheets: 'always',
  },
  trailingSlash: 'always',
  integrations: [
    sitemap({
      serialize(item) {
        item.lastmod = new Date();
        return item;
      },
      i18n: {
        defaultLocale: 'ja',
        locales: {
          ja: 'ja',
          ko: 'ko',
          en: 'en',
        },
      },
    }),
  ],
  markdown: {
    shikiConfig: {
      theme: 'material-theme-darker',
    },
    rehypePlugins: [
      [rehypeCallouts, { theme: 'github' }],
      [
        rehypeExternalLinks,
        { target: '_blank', rel: ['nofollow', 'noreferrer'] },
      ],
      rehypeInFeedAds,
      [
        rehypePicture,
        { publicDir: new URL('./public', import.meta.url).pathname },
      ],
    ],
  },
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          silenceDeprecations: ['import', 'global-builtin', 'color-functions'],
        },
      },
    },
  },
});

主要設定項目

site

site: 'https://deku.posstree.com',

サイトの最終デプロイURLです。サイトマップ生成、canonical URL、OGタグなどで使用されます。

output

output: 'static',

静的サイトとしてビルドします。GitHub Pagesにデプロイするには必ず'static'に設定する必要があります。

build.inlineStylesheets

build: {
  inlineStylesheets: 'always',
},

すべてのCSSをHTMLにインラインで含めます。別途のCSSファイルリクエストを減らして初期ロード速度を改善します。

trailingSlash

trailingSlash: 'always',

すべてのURLが/で終わるように設定します。/astro/installationではなく/astro/installation/になります。Jekyllで使用していたURL形式を維持するために設定しました。

integrations

integrations: [
  sitemap({ ... }),
],

@astrojs/sitemapプラグインで多言語サイトマップを自動生成します。詳細はSEO実装ポストで扱います。

markdown

マークダウン処理のための設定です。

  • shikiConfig:コードブロックのシンタックスハイライトにmaterial-theme-darkerテーマを使用します
  • rehypePlugins:マークダウンをHTMLに変換する時に適用されるプラグインです
    • rehype-callouts:GitHubスタイルのコールアウトブロックをサポート
    • rehype-external-links:外部リンクに自動的にtarget="_blank"rel="nofollow noreferrer"を追加
    • rehype-in-feed-ads:マークダウン内の<!-- ad -->コメントを広告ブロックに変換
    • rehype-picture:画像をAVIF/WebP形式の<picture>要素に自動変換

package.jsonスクリプト

ブログプロジェクトで使用するnpmスクリプトです。

{
  "name": "deku-blog",
  "type": "module",
  "version": "1.0.0",
  "scripts": {
    "dev": "astro dev",
    "build": "astro build && npx pagefind --site dist",
    "prepreview": "npm run build",
    "preview": "astro preview",
    "predeploy": "npm run share:sync",
    "deploy": "gh-pages -d dist -r git@personal:posstree/deku.posstree.com.git -t"
  },
  "dependencies": {
    "@astrojs/rss": "^4.0.0",
    "@astrojs/sitemap": "^3.3.0",
    "astro": "^5.17.1",
    "rehype-callouts": "^2.1.2",
    "rehype-external-links": "^3.0.0",
    "sass": "^1.80.0",
    "sharp": "^0.33.0"
  },
  "devDependencies": {
    "dotenv": "^16.6.1",
    "gh-pages": "^6.3.0",
    "pagefind": "^1.4.0"
  }
}

主要スクリプトの説明

スクリプトの主な機能は以下の通りです。

スクリプト説明
npm run dev開発サーバー起動。HMRで即座に反映
npm run buildプロダクションビルド + Pagefind検索インデックス生成
npm run previewビルドされたサイトをローカルでプレビュー
npm run deployGitHub Pagesにデプロイ

buildスクリプトでastro buildの後にnpx pagefind --site distを実行するのがポイントです。PagefindはビルドされたHTMLファイルを分析して検索インデックスを生成するため、必ずビルド後に実行する必要があります。

主要依存パッケージの説明

Astroプロジェクトで使用される主要パッケージと役割は以下の通りです。

パッケージ役割
astroコアフレームワーク
@astrojs/sitemap多言語サイトマップ自動生成
@astrojs/rssRSSフィード生成
sassSCSSプリプロセッサー
sharp画像変換(AVIF/WebP)
rehype-calloutsGitHubスタイルコールアウト
rehype-external-links外部リンク処理
gh-pagesGitHub Pagesデプロイ
pagefind静的検索

SCSS設定

このブログはSCSSを使用してスタイルを管理しています。AstroViteを内蔵しているため、sassパッケージをインストールするだけで別途の設定なしにSCSSを使用できます。

npm install sass

ただし、Sassの最新バージョンでdeprecatedされた機能を使用している場合、警告が発生することがあります。astro.config.mjsvite設定でこれを無視できます。

vite: {
  css: {
    preprocessorOptions: {
      scss: {
        silenceDeprecations: ['import', 'global-builtin', 'color-functions'],
      },
    },
  },
},

グローバルスタイルはsrc/styles/global.scssで管理し、レイアウトコンポーネントでimportして使用します。

---
// BaseLayout.astro
import '../styles/global.scss';
---

完了

今回の記事ではAstroプロジェクトのインストールと基本構成を見てきました。まとめると:

  • npm create astro@latestでプロジェクト作成
  • astro.config.mjsでサイトURL、静的ビルド、サイトマップ、マークダウンプラグイン設定
  • package.jsonでビルド、開発、デプロイスクリプト構成
  • SCSS設定およびdeprecation警告処理

次の記事Content Collectionsとマークダウンマイグレーションでは、JekyllのマークダウンファイルをAstroContent Collectionsにマイグレーションする方法を扱います。

シリーズ案内

このポストはJekyllからAstroへのマイグレーションシリーズの一部です。

  1. JekyllからAstroへマイグレーションした理由
  2. Astroのインストールとプロジェクト構成
  3. Content Collectionsとマークダウンマイグレーション
  4. 多言語(i18n)実装
  5. SEO実装
  6. 画像最適化 — カスタムrehypeプラグイン
  7. コメントシステム(Utterances)
  8. 広告連携(Google AdSense)
  9. Pagefindを利用した検索実装
  10. レイアウトとコンポーネントアーキテクチャ
  11. GitHub Pagesデプロイ
  12. ソーシャル共有自動化スクリプト
  13. トラブルシューティングとヒント

私のブログが役に立ちましたか?下にコメントを残してください。それは私にとって大きな大きな力になります!

アプリ広報

今見てるブログを作成たDekuが開発したアプリを使ってみてください。
Dekuが開発したアプリはFlutterで開発されています。

興味がある方はアプリをダウンロードしてアプリを使ってくれると本当に助かります。



SHARE
Twitter Facebook RSS