vite-plugin-compile-progress.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. export function progressTrackingPlugin() {
  2. let server
  3. const moduleStats = {
  4. total: 0,
  5. processed: 0,
  6. pending: new Set()
  7. }
  8. return {
  9. name: 'progress-tracking',
  10. apply: 'serve',
  11. enforce: 'pre',
  12. configureServer(_server) {
  13. server = _server
  14. },
  15. async transform(code, id) {
  16. if (server && id) {
  17. moduleStats.total++
  18. moduleStats.pending.add(id)
  19. server.ws.send('progress:update', {
  20. total: moduleStats.total,
  21. processed: moduleStats.processed,
  22. current: id
  23. })
  24. await server.waitForRequestsIdle(id)
  25. moduleStats.processed++
  26. moduleStats.pending.delete(id)
  27. server.ws.send('progress:update', {
  28. total: moduleStats.total,
  29. processed: moduleStats.processed,
  30. current: null
  31. })
  32. }
  33. },
  34. transformIndexHtml: {
  35. order: 'pre',
  36. handler(html, ctx) {
  37. return {
  38. html,
  39. tags: [
  40. {
  41. tag: 'style',
  42. children: `
  43. #vite-progress-bar {
  44. position: fixed;
  45. top: 0;
  46. left: 0;
  47. width: 0%;
  48. height: 3px;
  49. background: #646cff;
  50. transition: width 0.3s ease;
  51. z-index: 9999;
  52. opacity: 1;
  53. }
  54. #vite-progress-bar.complete {
  55. opacity: 0;
  56. transition: opacity 0.5s ease;
  57. }
  58. #vite-progress-status {
  59. position: fixed;
  60. top: 10px;
  61. right: 10px;
  62. background: rgba(0, 0, 0, 0.8);
  63. color: white;
  64. padding: 8px 12px;
  65. border-radius: 4px;
  66. font-size: 12px;
  67. font-family: monospace;
  68. z-index: 10000;
  69. display: none;
  70. }
  71. `,
  72. injectTo: 'head'
  73. },
  74. {
  75. tag: 'div',
  76. attrs: { id: 'vite-progress-bar' },
  77. injectTo: 'body-prepend'
  78. },
  79. {
  80. tag: 'div',
  81. attrs: { id: 'vite-progress-status' },
  82. children: 'Loading...',
  83. injectTo: 'body-prepend'
  84. },
  85. {
  86. tag: 'script',
  87. attrs: { type: 'module' },
  88. children: `
  89. if (import.meta.hot) {
  90. // 进度追踪状态
  91. let serverProgress = 0;
  92. let resourcesCompleted = 0;
  93. let estimatedTotal = 0;
  94. let isLoading = true;
  95. let completionTimer = null;
  96. let lastResourceTime = Date.now();
  97. let hasServerActivity = false;
  98. let serverActivityTimer = null;
  99. // DOM 元素引用
  100. const progressBar = document.getElementById('vite-progress-bar');
  101. const statusDisplay = document.getElementById('vite-progress-status');
  102. // 改进的预估算法
  103. function estimateResourceCount() {
  104. const scripts = document.querySelectorAll('script[src]').length;
  105. const links = document.querySelectorAll('link[href]').length;
  106. const styleSheets = document.querySelectorAll('link[rel="stylesheet"]').length;
  107. const preloadLinks = document.querySelectorAll('link[rel="preload"], link[rel="modulepreload"]').length;
  108. const baseEstimate = scripts + links + styleSheets + preloadLinks;
  109. const conservativeEstimate = Math.max(baseEstimate + 8, 12);
  110. return conservativeEstimate;
  111. }
  112. // 检测服务端活动
  113. function detectServerActivity() {
  114. hasServerActivity = true;
  115. if (serverActivityTimer) clearTimeout(serverActivityTimer);
  116. // 如果2秒内没有新的服务端活动,认为服务端编译已完成或无需编译
  117. serverActivityTimer = setTimeout(() => {
  118. if (serverProgress === 0) {
  119. console.log('No server compilation detected - using client-only mode');
  120. hasServerActivity = false;
  121. updateProgress();
  122. }
  123. }, 2000);
  124. }
  125. // 在 checkCompletion 函数中进一步优化完成条件
  126. function checkCompletion() {
  127. const now = Date.now();
  128. const timeSinceLastResource = now - lastResourceTime;
  129. // 添加详细的调试日志
  130. console.log('=== checkCompletion Debug ===');
  131. console.log('hasServerActivity:', hasServerActivity);
  132. console.log('serverProgress:', serverProgress);
  133. console.log('resourcesCompleted:', resourcesCompleted);
  134. console.log('estimatedTotal:', estimatedTotal);
  135. console.log('timeSinceLastResource:', timeSinceLastResource);
  136. console.log('isLoading:', isLoading);
  137. // 根据服务端活动情况调整完成条件
  138. if (!hasServerActivity) {
  139. console.log('Checking client-only completion conditions...');
  140. // 客户端模式下的完成条件更加宽松
  141. if (resourcesCompleted >= estimatedTotal * 0.8 && timeSinceLastResource > 1000) {
  142. console.log('✅ Client-only loading complete (80% threshold)');
  143. forceComplete();
  144. return;
  145. }
  146. // 如果进度超过95%且1秒无新资源,立即完成
  147. if (resourcesCompleted >= estimatedTotal * 0.95 && timeSinceLastResource > 1000) {
  148. console.log('✅ Client-only loading complete (95% threshold)');
  149. forceComplete();
  150. return;
  151. }
  152. // 如果进度超过97%且0.5秒无新资源,立即完成
  153. if (resourcesCompleted >= estimatedTotal * 0.97 && timeSinceLastResource > 500) {
  154. console.log('✅ Client-only loading complete (97% threshold)');
  155. forceComplete();
  156. return;
  157. }
  158. console.log('❌ Client-only conditions not met');
  159. } else {
  160. console.log('Checking mixed mode completion conditions...');
  161. // 有服务端编译时的完成条件
  162. if (serverProgress >= 1.0 && timeSinceLastResource > 1500) {
  163. console.log('✅ Server + client loading complete');
  164. forceComplete();
  165. return;
  166. }
  167. console.log('❌ Mixed mode conditions not met');
  168. console.log('serverProgress >= 1.0:', serverProgress >= 1.0);
  169. console.log('timeSinceLastResource > 1500:', timeSinceLastResource > 1500);
  170. }
  171. // 超时强制完成 - 进一步缩短超时时间
  172. if (timeSinceLastResource > 2000) {
  173. console.log('⏰ Force completing due to timeout (2s)');
  174. forceComplete();
  175. } else {
  176. console.log('⏳ Waiting for timeout, remaining:', 2000 - timeSinceLastResource, 'ms');
  177. }
  178. console.log('=== End checkCompletion Debug ===');
  179. }
  180. // 强制完成
  181. function forceComplete() {
  182. if (!isLoading) return;
  183. isLoading = false;
  184. progressBar.style.width = '100%';
  185. statusDisplay.style.display = 'none';
  186. progressBar.classList.add('complete');
  187. console.log('Loading completed!');
  188. setTimeout(() => {
  189. progressBar.style.display = 'none';
  190. }, 1000);
  191. }
  192. // 更新进度条和状态显示
  193. function updateProgress() {
  194. if (!progressBar || !statusDisplay || !isLoading) return;
  195. let totalProgress;
  196. if (!hasServerActivity && serverProgress === 0) {
  197. // 无服务端编译活动,100%依赖客户端资源
  198. const clientProgress = estimatedTotal > 0 ?
  199. Math.min(resourcesCompleted / estimatedTotal, 1.0) : 0;
  200. totalProgress = clientProgress * 100;
  201. console.log(\`Client-only mode: \${resourcesCompleted}/\${estimatedTotal} resources\`);
  202. } else {
  203. // 有服务端编译活动,使用混合权重
  204. const serverWeight = serverProgress < 1.0 ? 0.6 : 0.3;
  205. const clientWeight = serverProgress < 1.0 ? 0.4 : 0.7;
  206. const serverPart = serverProgress * serverWeight;
  207. const clientPart = estimatedTotal > 0 ?
  208. Math.min(resourcesCompleted / estimatedTotal, 1.0) * clientWeight : 0;
  209. totalProgress = (serverPart + clientPart) * 100;
  210. console.log(\`Mixed mode: Server \${Math.round(serverProgress * 100)}%, Client \${resourcesCompleted}/\${estimatedTotal}\`);
  211. }
  212. // 确保进度不会倒退
  213. const currentWidth = parseFloat(progressBar.style.width) || 0;
  214. totalProgress = Math.max(totalProgress, currentWidth);
  215. // 更新进度条
  216. progressBar.style.width = Math.min(totalProgress, 100) + '%';
  217. // 更新状态显示
  218. statusDisplay.style.display = 'block';
  219. const mode = hasServerActivity ? 'Mixed' : 'Client-only';
  220. statusDisplay.textContent =
  221. \`Loading... \${Math.round(totalProgress)}% (\${mode}: \${resourcesCompleted}/\${estimatedTotal})\`;
  222. console.log(\`Progress: Total \${Math.round(totalProgress)}%\`);
  223. // 如果接近完成,开始检测完成状态
  224. if (totalProgress >= 85) {
  225. if (completionTimer) clearTimeout(completionTimer);
  226. completionTimer = setTimeout(checkCompletion, 800);
  227. }
  228. }
  229. // 监听服务端编译进度
  230. import.meta.hot.on('progress:update', (data) => {
  231. detectServerActivity();
  232. serverProgress = data.total > 0 ? data.processed / data.total : 0;
  233. updateProgress();
  234. });
  235. // 使用 PerformanceObserver 监控资源加载完成
  236. if (window.PerformanceObserver) {
  237. const completedResources = new Set();
  238. const observer = new PerformanceObserver((list) => {
  239. for (const entry of list.getEntries()) {
  240. if (entry.entryType === 'resource') {
  241. const isRelevantResource =
  242. entry.initiatorType === 'script' ||
  243. entry.initiatorType === 'link' ||
  244. entry.initiatorType === 'css' ||
  245. entry.name.includes('.js') ||
  246. entry.name.includes('.css') ||
  247. entry.name.includes('.ts');
  248. if (isRelevantResource && !completedResources.has(entry.name)) {
  249. completedResources.add(entry.name);
  250. resourcesCompleted++;
  251. lastResourceTime = Date.now();
  252. // 更保守的总数调整策略
  253. if (resourcesCompleted > estimatedTotal * 0.95) {
  254. estimatedTotal = Math.max(estimatedTotal, resourcesCompleted + 1);
  255. }
  256. console.log(\`Resource completed: \${entry.name} (type: \${entry.initiatorType})\`);
  257. updateProgress();
  258. }
  259. }
  260. }
  261. });
  262. observer.observe({ entryTypes: ['resource'] });
  263. }
  264. // 初始化
  265. function initialize() {
  266. estimatedTotal = estimateResourceCount();
  267. lastResourceTime = Date.now();
  268. console.log(\`Estimated total resources: \${estimatedTotal}\`);
  269. // 显示初始状态
  270. if (statusDisplay) {
  271. statusDisplay.style.display = 'block';
  272. statusDisplay.textContent = \`Initializing... (0/\${estimatedTotal} resources)\`;
  273. }
  274. updateProgress();
  275. // 启动服务端活动检测
  276. setTimeout(() => {
  277. if (!hasServerActivity) {
  278. console.log('No server activity detected, switching to client-only mode');
  279. updateProgress();
  280. }
  281. }, 1000);
  282. }
  283. // 页面加载完成后的处理
  284. function handlePageLoad() {
  285. setTimeout(() => {
  286. if (resourcesCompleted > 0) {
  287. estimatedTotal = Math.max(resourcesCompleted + 1, estimatedTotal);
  288. console.log(\`Final estimated total: \${estimatedTotal}\`);
  289. }
  290. updateProgress();
  291. // 页面加载完成后,更积极地检测完成状态
  292. setTimeout(() => {
  293. if (isLoading && resourcesCompleted >= estimatedTotal * 0.8) {
  294. console.log('Page load complete, forcing finish');
  295. forceComplete();
  296. }
  297. }, 1000);
  298. }, 500);
  299. }
  300. // 根据文档状态初始化
  301. if (document.readyState === 'loading') {
  302. document.addEventListener('DOMContentLoaded', initialize);
  303. document.addEventListener('load', handlePageLoad);
  304. } else {
  305. setTimeout(initialize, 0);
  306. if (document.readyState === 'complete') {
  307. setTimeout(handlePageLoad, 100);
  308. } else {
  309. document.addEventListener('load', handlePageLoad);
  310. }
  311. }
  312. // HMR 更新时重置状态
  313. import.meta.hot.on('vite:beforeUpdate', () => {
  314. console.log('HMR update detected, maintaining progress tracking...');
  315. });
  316. }
  317. `,
  318. injectTo: 'body'
  319. }
  320. ]
  321. }
  322. }
  323. }
  324. }
  325. }