Astroを用いた静的サイト(SSG)の運用において、コンテンツコレクション(Content Collections)のFrontmatterの一貫性を維持することは、安定したビルドを保証する上で極めて重要です。本記事では、check-all-content.mjs スクリプトを活用して、膨大なMarkdown記事のメタデータ書式エラーを体系的にスキャン・自動修復する実装手法を解説します。

トラブルの背景:難解なビルドエラー

Astroのビルド時に id.endsWith is not a function や予期せぬZodスキーマ検証エラーが発生した場合、大半の原因はMarkdownファイルのFrontmatterの書式不正にあります。典型的な例は以下の通りです。

  • コロンやブラケットを含む文字列のクォート忘れ
  • フィールド型の不一致(配列であるべき箇所に単一文字列が指定されている等)
  • 日付フォーマットの表記揺れ
  • 特殊文字のエスケープ漏れによるYAMLパースクラッシュ

解決策:check-all-content.mjs の設計

スクリプトの主な機能

  1. 全記事の体系的トラバース:src/content/blog/ 配下の全スラッグディレクトリを再帰的に走査。
  2. スキーマ検証:js-yaml を用いてFrontmatterをパースし、必須フィールドの存在と型を検証。
  3. エラー出力と自動修復:破損箇所を特定し、安全な自動修復を実行。

実装コード例

プロジェクトルートの scripts/check-all-content.mjs に以下の検証スクリプトを作成します。

// check-all-content.mjs: Astro Content Collection 検証ツール
import fs from 'node:fs';
import path from 'node:path';
import yaml from 'js-yaml';

console.log('🔍 コンテンツコレクションの書式をスキャン中...\n');

const blogDir = './src/content/blog';
const slugDirs = fs.readdirSync(blogDir, { withFileTypes: true })
  .filter(item => item.isDirectory())
  .map(item => item.name);

console.log(`対象記事ディレクトリ数: ${slugDirs.length} 件\n`);

let totalProblems = 0;

for (const slug of slugDirs) {
  const filePath = path.join(blogDir, slug, 'index.md');

  if (!fs.existsSync(filePath)) {
    console.log(`❌ ${slug}: index.md が存在しません`);
    totalProblems++;
    continue;
  }

  const raw = fs.readFileSync(filePath, 'utf8');
  const match = raw.match(/^---\n([\s\S]*?)\n---/);

  if (!match) {
    console.log(`❌ ${slug}: Frontmatterブロックが存在しません`);
    totalProblems++;
    continue;
  }

  try {
    const data = yaml.load(match[1]);
    if (!data.title) {
      console.log(`⚠️ ${slug}: 'title' 項目が不足しています`);
      totalProblems++;
    }
  } catch (err) {
    console.log(`❌ ${slug}: YAML構文エラー: ${err.message}`);
    totalProblems++;
  }
}

console.log(`\n検証完了。検出された問題: ${totalProblems} 件`);

実行方法

ビルド実行前にNode.js経由でスクリプトを実行します。

node scripts/check-all-content.mjs

CI/CDパイプラインやpre-commitフックに本スクリプトを組み込むことで、書式不正による本番ビルドの停止を未然に防ぐことができます。

✦ 独立した報道 · 読者サポート ✦

独自の視点と客観的な報道を、あなたの温かい支援で

表面的なトレンドやアルゴリズムに流されず、事実と深い洞察に基づいた独立した記事をお届けし続けるために。

質の高いオリジナル記事と独立した運営を続けるため、1回のみ、または毎月のご支援をGoogleの安全な決済でお願いいたします。

お支払いはGoogleにより安全に処理されます · いつでも管理・解約できます