vite-plugin-compile-progress.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. // DOM 元素引用
  98. const progressBar = document.getElementById('vite-progress-bar');
  99. const statusDisplay = document.getElementById('vite-progress-status');
  100. // 改进的预估算法
  101. function estimateResourceCount() {
  102. const scripts = document.querySelectorAll('script[src]').length;
  103. const links = document.querySelectorAll('link[href]').length;
  104. const styleSheets = document.querySelectorAll('link[rel="stylesheet"]').length;
  105. const preloadLinks = document.querySelectorAll('link[rel="preload"], link[rel="modulepreload"]').length;
  106. // 更保守的预估,避免过度增长
  107. const baseEstimate = scripts + links + styleSheets + preloadLinks;
  108. const conservativeEstimate = Math.max(baseEstimate + 10, 15); // 只加10个缓冲
  109. return conservativeEstimate;
  110. }
  111. // 检测是否完成加载
  112. function checkCompletion() {
  113. const now = Date.now();
  114. const timeSinceLastResource = now - lastResourceTime;
  115. // 如果2秒内没有新资源加载,且服务端完成,认为加载完成
  116. if (serverProgress >= 1.0 && timeSinceLastResource > 2000) {
  117. console.log('Loading appears to be complete - no new resources for 2 seconds');
  118. forceComplete();
  119. return;
  120. }
  121. // 如果进度超过98%且3秒内没有新资源,强制完成
  122. if (serverProgress >= 1.0 && resourcesCompleted >= estimatedTotal * 0.9 && timeSinceLastResource > 3000) {
  123. console.log('Force completing - high progress with no recent activity');
  124. forceComplete();
  125. return;
  126. }
  127. }
  128. // 强制完成
  129. function forceComplete() {
  130. if (!isLoading) return;
  131. isLoading = false;
  132. progressBar.style.width = '100%';
  133. statusDisplay.style.display = 'none';
  134. progressBar.classList.add('complete');
  135. console.log('Loading completed!');
  136. setTimeout(() => {
  137. progressBar.style.display = 'none';
  138. }, 1000);
  139. }
  140. // 更新进度条和状态显示
  141. function updateProgress() {
  142. if (!progressBar || !statusDisplay || !isLoading) return;
  143. // 动态调整权重:服务端完成后,客户端权重增加
  144. const serverWeight = serverProgress < 1.0 ? 0.6 : 0.3;
  145. const clientWeight = serverProgress < 1.0 ? 0.4 : 0.7;
  146. const serverPart = serverProgress * serverWeight;
  147. const clientPart = estimatedTotal > 0 ?
  148. Math.min(resourcesCompleted / estimatedTotal, 1.0) * clientWeight : 0;
  149. let totalProgress = Math.min((serverPart + clientPart) * 100, 100);
  150. // 如果服务端完成且客户端接近完成,给予额外加成
  151. if (serverProgress >= 1.0 && resourcesCompleted >= estimatedTotal * 0.8) {
  152. totalProgress = Math.max(totalProgress, 95);
  153. }
  154. // 更新进度条
  155. progressBar.style.width = totalProgress + '%';
  156. // 更新状态显示
  157. statusDisplay.style.display = 'block';
  158. statusDisplay.textContent =
  159. \`Loading... \${Math.round(totalProgress)}% (\${resourcesCompleted}/\${estimatedTotal} resources)\`;
  160. console.log(\`Progress: Server \${Math.round(serverProgress * 100)}%, Resources \${resourcesCompleted}/\${estimatedTotal}, Total \${Math.round(totalProgress)}%\`);
  161. // 如果接近完成,开始检测完成状态
  162. if (totalProgress >= 95) {
  163. if (completionTimer) clearTimeout(completionTimer);
  164. completionTimer = setTimeout(checkCompletion, 1000);
  165. }
  166. }
  167. // 监听服务端编译进度
  168. import.meta.hot.on('progress:update', (data) => {
  169. serverProgress = data.total > 0 ? data.processed / data.total : 0;
  170. updateProgress();
  171. });
  172. // 使用 PerformanceObserver 监控资源加载完成
  173. if (window.PerformanceObserver) {
  174. const completedResources = new Set();
  175. const observer = new PerformanceObserver((list) => {
  176. for (const entry of list.getEntries()) {
  177. if (entry.entryType === 'resource') {
  178. const isRelevantResource =
  179. entry.initiatorType === 'script' ||
  180. entry.initiatorType === 'link' ||
  181. entry.initiatorType === 'css' ||
  182. entry.name.includes('.js') ||
  183. entry.name.includes('.css') ||
  184. entry.name.includes('.ts');
  185. if (isRelevantResource && !completedResources.has(entry.name)) {
  186. completedResources.add(entry.name);
  187. resourcesCompleted++;
  188. lastResourceTime = Date.now();
  189. // 更保守的总数调整策略
  190. if (resourcesCompleted > estimatedTotal * 0.9) {
  191. estimatedTotal = Math.max(estimatedTotal, resourcesCompleted + 3); // 只加3个缓冲
  192. }
  193. console.log(\`Resource completed: \${entry.name} (type: \${entry.initiatorType})\`);
  194. updateProgress();
  195. }
  196. }
  197. }
  198. });
  199. observer.observe({ entryTypes: ['resource'] });
  200. }
  201. // 初始化
  202. function initialize() {
  203. estimatedTotal = estimateResourceCount();
  204. lastResourceTime = Date.now();
  205. console.log(\`Estimated total resources: \${estimatedTotal}\`);
  206. // 显示初始状态
  207. if (statusDisplay) {
  208. statusDisplay.style.display = 'block';
  209. statusDisplay.textContent = \`Initializing... (0/\${estimatedTotal} resources)\`;
  210. }
  211. updateProgress();
  212. }
  213. // 页面加载完成后的处理
  214. function handlePageLoad() {
  215. setTimeout(() => {
  216. // 最终调整预估值
  217. if (resourcesCompleted > 0) {
  218. estimatedTotal = Math.max(resourcesCompleted + 2, estimatedTotal);
  219. console.log(\`Final estimated total: \${estimatedTotal}\`);
  220. }
  221. updateProgress();
  222. // 开始完成检测
  223. setTimeout(checkCompletion, 2000);
  224. }, 1000);
  225. }
  226. // 根据文档状态初始化
  227. if (document.readyState === 'loading') {
  228. document.addEventListener('DOMContentLoaded', initialize);
  229. document.addEventListener('load', handlePageLoad);
  230. } else {
  231. setTimeout(initialize, 0);
  232. if (document.readyState === 'complete') {
  233. setTimeout(handlePageLoad, 100);
  234. } else {
  235. document.addEventListener('load', handlePageLoad);
  236. }
  237. }
  238. // HMR 更新时重置状态
  239. import.meta.hot.on('vite:beforeUpdate', () => {
  240. console.log('HMR update detected, maintaining progress tracking...');
  241. });
  242. }
  243. `,
  244. injectTo: 'body'
  245. }
  246. ]
  247. }
  248. }
  249. }
  250. }
  251. }