|
| 1 | +#!/usr/bin/env node |
| 2 | +// 修 @nuxtjs/sitemap v7 + i18n + baseURL 已知 bug: |
| 3 | +// 預設 sitemap.xml 變成 HTML meta-refresh 重導到 /sitemap_index.xml, |
| 4 | +// 但 redirect URL 缺 baseURL 前綴 → 爬蟲 follow 後 404。 |
| 5 | +// |
| 6 | +// 此腳本在 nuxt generate 之後執行(postgenerate hook): |
| 7 | +// 1. 刪掉 .output/public/sitemap.xml/ 目錄 (含內部的 redirect index.html) |
| 8 | +// 2. 把 .output/public/sitemap_index.xml 的內容複製成 .output/public/sitemap.xml |
| 9 | +// |
| 10 | +// Google/Bing 都接受 sitemap.xml 本身為 sitemap index 檔案,不需另外指向。 |
| 11 | + |
| 12 | +import fs from 'node:fs' |
| 13 | +import path from 'node:path' |
| 14 | +import { fileURLToPath } from 'node:url' |
| 15 | + |
| 16 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)) |
| 17 | +const SITE_DIR = path.resolve(__dirname, '..') |
| 18 | +const PUBLIC_DIR = path.join(SITE_DIR, '.output', 'public') |
| 19 | + |
| 20 | +const sitemapXmlDir = path.join(PUBLIC_DIR, 'sitemap.xml') |
| 21 | +const sitemapIndexFile = path.join(PUBLIC_DIR, 'sitemap_index.xml') |
| 22 | +const sitemapXmlFile = sitemapXmlDir // will become a file after fix |
| 23 | + |
| 24 | +if (!fs.existsSync(PUBLIC_DIR)) { |
| 25 | + console.error(`[fix-sitemap] .output/public not found — run nuxt generate first`) |
| 26 | + process.exit(1) |
| 27 | +} |
| 28 | + |
| 29 | +if (!fs.existsSync(sitemapIndexFile)) { |
| 30 | + console.error(`[fix-sitemap] sitemap_index.xml not found — sitemap module did not generate it`) |
| 31 | + process.exit(1) |
| 32 | +} |
| 33 | + |
| 34 | +// 1. 若 sitemap.xml 是目錄,移除它 |
| 35 | +if (fs.existsSync(sitemapXmlDir)) { |
| 36 | + const stat = fs.statSync(sitemapXmlDir) |
| 37 | + if (stat.isDirectory()) { |
| 38 | + fs.rmSync(sitemapXmlDir, { recursive: true, force: true }) |
| 39 | + console.log('[fix-sitemap] removed buggy sitemap.xml/ redirect directory') |
| 40 | + } else if (stat.isFile()) { |
| 41 | + // 已經是檔案(可能其他工具修過了),跳過 |
| 42 | + console.log('[fix-sitemap] sitemap.xml already a file — skipping') |
| 43 | + process.exit(0) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// 2. 把 sitemap_index.xml 內容複製成 sitemap.xml |
| 48 | +fs.copyFileSync(sitemapIndexFile, sitemapXmlFile) |
| 49 | +const size = fs.statSync(sitemapXmlFile).size |
| 50 | +console.log(`[fix-sitemap] sitemap.xml now contains sitemap index (${size} bytes)`) |
0 commit comments