llms.txt для Remix
Два подхода для Remix: статический файл без дополнительной настройки в public/ или ресурсный маршрут app/routes/llms[.]txt.ts, возвращающий Response в виде обычного текста, при необходимости сгенерированного из вашего контента.
Последнее обновление:
Вариант 1: статический файл в public/
Remix обслуживает всё в public/ каталог статически в корне вашего сайта. Поместите файл
по адресу public/llms.txt, дополнительная настройка маршрутизации не требуется.
# Remix static file approach
#
# Place your file at: public/llms.txt
# Remix (and the underlying Node/Cloudflare/Vercel adapter)
# serves everything in public/ at the root of your site.
#
# Project structure:
# your-remix-app/
# ├── public/
# │ └── llms.txt ← add this
# ├── app/
# └── remix.config.js (or vite.config.ts)
Этот подход работает со всеми адаптерами Remix: @remix-run/node, @remix-run/cloudflare, @remix-run/vercel, и @remix-run/netlify. Статический файл имеет приоритет над любым совпадающим маршрутом.
Вариант 2: маршрут ресурса
Создайте маршрут ресурса в app/routes/llms[.]txt.ts. Этот [.] синтаксис экранирует точку в имени файла, чтобы Remix сопоставил её с URL-путём /llms.txt. Экспортируйте loader функцию, возвращающую Response с правильным Content-Type.
// app/routes/llms[.]txt.ts
// Remix resource route, the [.] escapes the dot in the filename
// This file is served at exactly /llms.txt
import type { LoaderFunctionArgs } from '@remix-run/node';
export async function loader({ request }: LoaderFunctionArgs) {
const content = `# Your Site
> One-sentence description of what your site or product does.
## Documentation
- [Getting Started](https://yoursite.com/docs/start): Install and configure.
- [API Reference](https://yoursite.com/docs/api): Full endpoint catalog.
## Product
- [Overview](https://yoursite.com/product): Features and capabilities.
- [Pricing](https://yoursite.com/pricing): Plans and billing.
## Optional
- [Changelog](https://yoursite.com/changelog): Release history.
- [GitHub](https://github.com/your-org/your-repo): Source code.
`;
return new Response(content, {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
},
});
}
Для динамической генерации из слоя контента получайте документы в загрузчике и программно создавайте список ссылок Markdown:
// app/routes/llms[.]txt.ts
// Generate from your content / MDX files
import type { LoaderFunctionArgs } from '@remix-run/node';
import { getAllDocs } from '~/models/docs.server';
export async function loader({ request }: LoaderFunctionArgs) {
// Fetch your documentation index from a DB or file system
const docs = await getAllDocs();
const links = docs
.map((doc) => `- [${doc.title}](https://yoursite.com/docs/${doc.slug}/): ${doc.summary}`)
.join('\n');
const body = [
'# Your Site',
'',
'> One-sentence summary of your project.',
'',
'## Documentation',
'',
links,
].join('\n');
return new Response(body, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
},
});
}
Подход с плагином Vite
Если вы используете Remix с Vite (по умолчанию для Remix v2.7+), можно сгенерировать llms.txt в рамках сборки с помощью плагина Vite. Созданный файл помещается в каталог
результатов сборки и обслуживается как статический ресурс. Это сочетает простоту статического файла
с доступом к содержимому во время сборки.
import { vitePlugin as remix } from '@remix-run/dev';
import { defineConfig } from 'vite';
import { writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
// Simple Vite plugin to generate llms.txt at build time
function llmsTxtPlugin() {
return {
name: 'generate-llms-txt',
buildStart() {
const content = `# Your Site\n\n> Summary.\n\n## Documentation\n\n- [Docs](https://yoursite.com/docs): Guide.\n`;
writeFileSync(resolve(__dirname, 'public/llms.txt'), content, 'utf-8');
},
};
}
export default defineConfig({
plugins: [remix(), llmsTxtPlugin()],
}); Проверить
После развёртывания убедитесь, что файл обслуживается корректно:
curl -I https://yoursite.com/llms.txt
# Expected:
# HTTP/2 200
# content-type: text/plain; charset=utf-8
curl https://yoursite.com/llms.txt | head -5 Связанные руководства
- Как создать llms.txt, шаблоны и контрольный список.
- Справочник формата llms.txt, подробности спецификации.
- Руководство Vercel, разверните Remix в Vercel.
- Руководство по Cloudflare Pages, Remix в Cloudflare.
- Валидатор · Генератор.