check-build-vitepress.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env ts-node
  2. import fs from 'fs';
  3. import path from 'path';
  4. import { fileURLToPath } from 'url';
  5. import { execSync } from 'child_process';
  6. const __filename = fileURLToPath(import.meta.url);
  7. const __dirname = path.dirname(__filename);
  8. const pkgName = 'vitepress'; // 本地包名
  9. const workspaceRoot = path.resolve(__dirname, '.');
  10. const pkgPath = path.resolve(workspaceRoot, 'packages', pkgName);
  11. const distPath = path.resolve(pkgPath, 'dist');
  12. const srcPath = path.resolve(pkgPath, 'src');
  13. // 遍历目录文件的修改时间
  14. function getAllTsFileMtimeMs(dirPath) {
  15. const results: number[] = [];
  16. function walk(currentPath) {
  17. const entries = fs.readdirSync(currentPath, { withFileTypes: true });
  18. for (const entry of entries) {
  19. const fullPath = path.join(currentPath, entry.name);
  20. if (entry.isDirectory()) {
  21. walk(fullPath); // 递归处理子目录
  22. } else if (entry.isFile() && entry.name.endsWith('.ts')) {
  23. const stat = fs.statSync(fullPath);
  24. results.push(stat.mtimeMs);
  25. }
  26. }
  27. }
  28. walk(dirPath);
  29. return results;
  30. }
  31. // 检查 dist 是否存在
  32. function hasBuilt(): boolean {
  33. return fs.existsSync(distPath);
  34. }
  35. // 检查 src 是否更新过
  36. function isSourceNewerThanDist(): boolean {
  37. if (!fs.existsSync(distPath)) return true;
  38. const distMtime = fs.statSync(distPath).mtimeMs;
  39. const srcFiles = getAllTsFileMtimeMs(srcPath)
  40. console.log("distMtime: ", distMtime)
  41. console.log("srcFiles: ", srcFiles)
  42. return Math.max(...srcFiles) > distMtime;
  43. }
  44. function buildPackage() {
  45. console.log(`[vitepress] 正在构建本地包 "${pkgName}"...`);
  46. execSync(`pnpm --filter ${pkgName} build`, { stdio: 'inherit' });
  47. }
  48. // 主流程
  49. (function main() {
  50. if (!hasBuilt() || isSourceNewerThanDist()) {
  51. buildPackage();
  52. } else {
  53. console.log(`[vitepress] 构建已是最新,跳过构建`);
  54. }
  55. })();