|
| 1 | +import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync } from "fs"; |
| 2 | +import { join, dirname, basename, extname } from "path"; |
| 3 | +import { fileURLToPath } from "url"; |
| 4 | + |
| 5 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 6 | +const distDir = join(__dirname, "..", "src", ".vitepress", "dist"); |
| 7 | + |
| 8 | +// 递归处理所有 HTML 文件,为 cleanUrls 创建目录结构 |
| 9 | +function createCleanUrlStructure(dir) { |
| 10 | + const files = readdirSync(dir); |
| 11 | + |
| 12 | + for (const file of files) { |
| 13 | + const fullPath = join(dir, file); |
| 14 | + const stat = statSync(fullPath); |
| 15 | + |
| 16 | + if (stat.isDirectory()) { |
| 17 | + createCleanUrlStructure(fullPath); |
| 18 | + } else if ( |
| 19 | + file.endsWith(".html") && |
| 20 | + file !== "index.html" && |
| 21 | + file !== "404.html" && |
| 22 | + file !== "200.html" |
| 23 | + ) { |
| 24 | + // 例如: docs/1.1-QuickStarted.html -> docs/1.1-QuickStarted/index.html |
| 25 | + const nameWithoutExt = basename(file, ".html"); |
| 26 | + const targetDir = join(dir, nameWithoutExt); |
| 27 | + |
| 28 | + if (!existsSync(targetDir)) { |
| 29 | + mkdirSync(targetDir, { recursive: true }); |
| 30 | + } |
| 31 | + |
| 32 | + const targetFile = join(targetDir, "index.html"); |
| 33 | + copyFileSync(fullPath, targetFile); |
| 34 | + console.log(`✓ Created ${targetFile}`); |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +// 创建 SPA fallback |
| 40 | +const indexHtml = join(distDir, "index.html"); |
| 41 | +const fallback200 = join(distDir, "200.html"); |
| 42 | +const fallback404 = join(distDir, "404.html"); |
| 43 | + |
| 44 | +if (existsSync(indexHtml)) { |
| 45 | + copyFileSync(indexHtml, fallback200); |
| 46 | + console.log("✓ Created 200.html for SPA fallback"); |
| 47 | +} |
| 48 | + |
| 49 | +if (existsSync(fallback404)) { |
| 50 | + // 404.html 指向 index.html 的内容以支持 SPA 路由 |
| 51 | + copyFileSync(indexHtml, fallback404); |
| 52 | + console.log("✓ Updated 404.html for SPA fallback"); |
| 53 | +} |
| 54 | + |
| 55 | +// 为 cleanUrls 创建目录结构 |
| 56 | +console.log("\nCreating clean URL directory structure..."); |
| 57 | +createCleanUrlStructure(distDir); |
| 58 | +console.log("\n✓ Build post-processing complete!"); |
0 commit comments