|
| 1 | +import type { NextConfig } from "next"; |
| 2 | + |
| 3 | +type LlmsTxtPluginOptions = { |
| 4 | + enabled?: boolean; |
| 5 | + generateOnBuild?: boolean; |
| 6 | +}; |
| 7 | + |
| 8 | +/** |
| 9 | + * Next.js plugin that generates llms.txt at build time |
| 10 | + * |
| 11 | + * This plugin integrates with the Next.js build process to automatically |
| 12 | + * generate an llms.txt file that follows the llms.txt specification. |
| 13 | + * |
| 14 | + * @param options - Plugin configuration options |
| 15 | + * @returns Next.js config wrapper function |
| 16 | + */ |
| 17 | +export function withLlmsTxt(options: LlmsTxtPluginOptions = {}) { |
| 18 | + const { enabled = true, generateOnBuild = true } = options; |
| 19 | + |
| 20 | + return (nextConfig: NextConfig = {}): NextConfig => { |
| 21 | + if (!enabled) { |
| 22 | + return nextConfig; |
| 23 | + } |
| 24 | + |
| 25 | + return { |
| 26 | + ...nextConfig, |
| 27 | + webpack: (config, context) => { |
| 28 | + // Only run during production build or when explicitly enabled |
| 29 | + if (generateOnBuild && !context.isServer) { |
| 30 | + // Add a custom plugin that runs after compilation |
| 31 | + config.plugins = config.plugins || []; |
| 32 | + config.plugins.push({ |
| 33 | + apply: (compiler: { |
| 34 | + hooks: { |
| 35 | + afterEmit: { |
| 36 | + tapPromise: ( |
| 37 | + name: string, |
| 38 | + callback: () => Promise<void> |
| 39 | + ) => void; |
| 40 | + }; |
| 41 | + }; |
| 42 | + options: { name: string }; |
| 43 | + }) => { |
| 44 | + compiler.hooks.afterEmit.tapPromise("LlmsTxtPlugin", async () => { |
| 45 | + // Only generate once (not on every rebuild) |
| 46 | + if (compiler.options.name === "client") { |
| 47 | + try { |
| 48 | + // Dynamic import to avoid bundling issues |
| 49 | + const { generateLlmsTxt } = await import( |
| 50 | + "../scripts/generate-llmstxt.js" |
| 51 | + ); |
| 52 | + |
| 53 | + await generateLlmsTxt(); |
| 54 | + } catch (_error) { |
| 55 | + // Don't fail the build if llms.txt generation fails |
| 56 | + } |
| 57 | + } |
| 58 | + }); |
| 59 | + }, |
| 60 | + }); |
| 61 | + } |
| 62 | + |
| 63 | + // Call the original webpack function if it exists |
| 64 | + if (typeof nextConfig.webpack === "function") { |
| 65 | + return nextConfig.webpack(config, context); |
| 66 | + } |
| 67 | + |
| 68 | + return config; |
| 69 | + }, |
| 70 | + }; |
| 71 | + }; |
| 72 | +} |
0 commit comments