Gatsby 的 llms.txt

Gatsby 有两种方法:在 static/ 中放置一个零配置静态文件,或使用 GraphQL 数据层在 gatsby-node.js 中以编程方式生成文件,并根据你的内容构建链接。

最近更新:

选项 1:static/ 中的静态文件

Gatsby 会把 static/ 目录直接复制到 public/ 构建输出。将文件放在 static/llms.txt 并且它会在 /llms.txt 之后 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 中生成

对于文档页面来源于 Markdown、MDX 或通过 Gatsby 数据层接入 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

相关指南

来源