|
| 1 | +import { addPrerenderRoutes, defineNuxtModule, createResolver } from '@nuxt/kit' |
| 2 | +import { readdirSync, statSync } from 'fs' |
| 3 | +import { join, relative } from 'path' |
| 4 | + |
| 5 | +export default defineNuxtModule({ |
| 6 | + meta: { |
| 7 | + name: 'pre-render-raw-routes', |
| 8 | + configKey: 'preRenderRawRoutes', |
| 9 | + }, |
| 10 | + setup(options, nuxt) { |
| 11 | + const { resolve } = createResolver(import.meta.url) |
| 12 | + const contentDir = resolve(nuxt.options.rootDir, 'content/docs') |
| 13 | + |
| 14 | + // Remove leading number and dot from names (e.g., "1.getting-started" -> "getting-started") |
| 15 | + function cleanName(name: string): string { |
| 16 | + return name.replace(/^\d+\./, '') |
| 17 | + } |
| 18 | + |
| 19 | + // Recursively get all .md files |
| 20 | + function getMarkdownFiles(dir: string, basePath: string = ''): string[] { |
| 21 | + const files: string[] = [] |
| 22 | + try { |
| 23 | + const entries = readdirSync(dir, { withFileTypes: true }) |
| 24 | + for (const entry of entries) { |
| 25 | + const fullPath = join(dir, entry.name) |
| 26 | + const cleanedName = cleanName(entry.name) |
| 27 | + const relativePath = join(basePath, cleanedName) |
| 28 | + |
| 29 | + if (entry.isDirectory()) { |
| 30 | + files.push(...getMarkdownFiles(fullPath, relativePath)) |
| 31 | + } else if (entry.isFile() && entry.name.endsWith('.md') && entry.name.includes('index.md')) { |
| 32 | + // For index.md, use the directory path (basePath) instead of including "index" |
| 33 | + const route = basePath ? `/${basePath}` : '/' |
| 34 | + files.push(route) |
| 35 | + } else if (entry.isFile() && entry.name.endsWith('.md') && entry.name !== 'index.md') { |
| 36 | + const route = `/${relativePath.replace(/\.md$/, '')}` |
| 37 | + files.push(route) |
| 38 | + } |
| 39 | + } |
| 40 | + } catch (error) { |
| 41 | + // Directory might not exist or be accessible |
| 42 | + console.warn(`Could not read directory ${dir}:`, error) |
| 43 | + } |
| 44 | + return files |
| 45 | + } |
| 46 | + |
| 47 | + const routes = getMarkdownFiles(contentDir) |
| 48 | + console.log(routes); |
| 49 | + const rawRoutes = routes.map(route => `/raw/docs${route}.md`) |
| 50 | + |
| 51 | + addPrerenderRoutes(rawRoutes) |
| 52 | + }, |
| 53 | +}) |
0 commit comments