Gatsby向けllms.txt

Gatsby には2つの方法があります。static/ に設定不要の静的ファイルを置く方法と、GraphQL データレイヤーを使って gatsby-node.js でプログラムにより生成し、コンテンツからリンクを構築する方法です。

最終更新:

オプション 1: static/ ディレクトリ内の静的ファイル

Gatsbyは、 static/ ディレクトリを直接 public/ ビルド出力です。ファイルを static/llms.txt とすれば、 /llms.txt after gatsby build.

static/llms.txt, directory structure
# Gatsby static file approach
#
# Place your file at: static/llms.txt
# Gatsby copies everything in static/ directly to the public/ build output.
#
# Project structure:
# your-gatsby-site/
# ├── static/
# │   └── llms.txt   ← add this
# ├── src/
# └── gatsby-config.js

この方法ではコード変更が不要で、Gatsbyのすべてのデプロイ先で利用できます: Netlify, Vercel, Cloudflare Pages, AWS Amplify、およびセルフホスト。

選択肢2:gatsby-node.jsで生成

ドキュメントページが、Gatsbyのデータレイヤーを介してMarkdown、MDX、またはCMSから取得されているサイトについては、 以下の onPostBuild ライフサイクルフック gatsby-node.js 生成するために llms.txt 。これにより、ビルド完了後も リンク一覧が常にコンテンツと同期します。

gatsby-node.js
// gatsby-node.js
// Generate llms.txt from your GraphQL data layer
const { writeFileSync } = require('fs');
const { resolve } = require('path');

exports.onPostBuild = async ({ graphql }) => {
  // Query your documentation pages (adjust the query to your data model)
  const result = await graphql(`
    query {
      allMarkdownRemark(
        filter: { frontmatter: { collection: { eq: "docs" } } }
        sort: { frontmatter: { order: ASC } }
      ) {
        nodes {
          frontmatter {
            title
            description
          }
          fields {
            slug
          }
        }
      }
    }
  `);

  if (result.errors) {
    throw result.errors;
  }

  const docs = result.data.allMarkdownRemark.nodes;
  const siteUrl = 'https://yoursite.com';

  const links = docs
    .map(
      (doc) =>
        `- [${doc.frontmatter.title}](${siteUrl}/docs/${doc.fields.slug}/): ${doc.frontmatter.description ?? ''}`
    )
    .join('\n');

  const content = [
    '# Your Site',
    '',
    '> One-sentence description of your project.',
    '',
    '## Documentation',
    '',
    links,
    '',
    '## Optional',
    '',
    `- [Changelog](${siteUrl}/changelog/): Release history.`,
  ].join('\n');

  // Write to public/ (Gatsby's build output directory)
  writeFileSync(resolve(__dirname, 'public', 'llms.txt'), content, 'utf-8');
};

onPostBuild フックは同じ graphql 関数がページクエリで使用されています。 データモデルに合わせてクエリを調整してください。この例では allMarkdownRemark しかし、 任意の Gatsby ソースプラグインに対してクエリを実行することは可能です(allMdx, allContentfulPageなど)。

Gatsbyプラグイン方式

プラグアンドプレイ型のソリューションをご希望の場合は、コミュニティが提供するいくつかのプラグインが生成します llms.txt 自動的に生成します。npm で gatsby-plugin-llms-txt。または、上記の gatsby-node.js は十分に単純なため、ほとんどの プロジェクトではカスタムプラグインを追加してもあまり利点はありません。

次も使用できます: gatsby-plugin-sitemap を参考にしており、同じ onPostBuild XML ファイルを作成するためのテンプレート public/.

検証

Build and verify
# Build
gatsby build

# Check generated file
cat public/llms.txt | head -10

# After deploying, verify the live URL
curl -I https://yoursite.com/llms.txt
# Expected: content-type: text/plain; charset=utf-8

関連ガイド

ソース