import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const dist = path.join(root, 'dist'); const siteSrc = path.join(root, 'IDE官网'); const legacyLoginDir = path.join(dist, 'login'); const siteDir = path.join(dist, 'site'); /** Avoid fs.cpSync merge into dist/assets (conflicts with Vite + can crash on Windows). */ function copyDirSync(src, dest, options = {}) { const { skipDirNames = new Set() } = options; fs.mkdirSync(dest, { recursive: true }); for (const entry of fs.readdirSync(src, { withFileTypes: true })) { if (entry.isDirectory() && skipDirNames.has(entry.name)) continue; const srcPath = path.join(src, entry.name); const destPath = path.join(dest, entry.name); if (entry.isDirectory()) { copyDirSync(srcPath, destPath, options); continue; } if (entry.isFile()) { fs.copyFileSync(srcPath, destPath); } } } /** 生产环境首页在 /,静态资源在 /site/assets/;勿用 base href(会把地址栏带到 /site/) */ function rewriteSiteAssetPaths(content) { return content .replace(/((?:href|src)=["'])assets\//g, '$1/site/assets/') .replace(/(["'])assets\//g, '$1/site/assets/'); } if (fs.existsSync(legacyLoginDir)) { fs.rmSync(legacyLoginDir, { recursive: true, force: true }); console.log('[postbuild] removed dist/login (conflicts with SPA route /login)'); } function copyOfficialSite() { if (!fs.existsSync(siteSrc) || !fs.existsSync(dist)) { return; } if (fs.existsSync(siteDir)) { fs.rmSync(siteDir, { recursive: true, force: true }); } copyDirSync(siteSrc, siteDir, { skipDirNames: new Set(['.well-known']), }); for (const rel of ['index.html', '404.html', '9610.html']) { const filePath = path.join(siteDir, rel); if (!fs.existsSync(filePath)) continue; const html = fs.readFileSync(filePath, 'utf8'); fs.writeFileSync(filePath, rewriteSiteAssetPaths(html), 'utf8'); } const jsDir = path.join(siteDir, 'assets', 'js'); if (fs.existsSync(jsDir)) { for (const name of fs.readdirSync(jsDir)) { if (!name.endsWith('.js')) continue; const filePath = path.join(jsDir, name); const js = fs.readFileSync(filePath, 'utf8'); if (!js.includes('assets/')) continue; fs.writeFileSync(filePath, rewriteSiteAssetPaths(js), 'utf8'); } } const src9610 = path.join(siteSrc, '9610.html'); if (fs.existsSync(src9610)) { fs.copyFileSync(src9610, path.join(dist, '9610.html')); } console.log('[postbuild] copied official site to dist/site (assets under /site/assets)'); } copyOfficialSite();