2
0

vite-plugin-compile-progress.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. // 检测是否完成加载
  126. function checkCompletion() {
  127. const now = Date.now();
  128. const timeSinceLastResource = now - lastResourceTime;
  129. // 根据服务端活动情况调整完成条件
  130. if (!hasServerActivity) {
  131. // 无服务端编译时,主要依赖客户端资源
  132. if (resourcesCompleted >= estimatedTotal * 0.85 && timeSinceLastResource > 1500) {
  133. console.log('Client-only loading complete (85% threshold)');
  134. forceComplete();
  135. return;
  136. }
  137. // 如果进度超过90%且1.5秒无新资源,强制完成
  138. if (resourcesCompleted >= estimatedTotal * 0.9 && timeSinceLastResource > 1500) {
  139. console.log('Client-only loading complete (90% threshold)');
  140. forceComplete();
  141. return;
  142. }
  143. } else {
  144. // 有服务端编译时,需要服务端完成
  145. if (serverProgress >= 1.0 && timeSinceLastResource > 2000) {
  146. console.log('Server + client loading complete');
  147. forceComplete();
  148. return;
  149. }
  150. }
  151. // 超时强制完成 - 缩短超时时间
  152. if (timeSinceLastResource > 3000) {
  153. console.log('Force completing due to timeout (3s)');
  154. forceComplete();
  155. }
  156. }
  157. // 强制完成
  158. function forceComplete() {
  159. if (!isLoading) return;
  160. isLoading = false;
  161. progressBar.style.width = '100%';
  162. statusDisplay.style.display = 'none';
  163. progressBar.classList.add('complete');
  164. console.log('Loading completed!');
  165. setTimeout(() => {
  166. progressBar.style.display = 'none';
  167. }, 1000);
  168. }
  169. // 更新进度条和状态显示
  170. function updateProgress() {
  171. if (!progressBar || !statusDisplay || !isLoading) return;
  172. let totalProgress;
  173. if (!hasServerActivity && serverProgress === 0) {
  174. // 无服务端编译活动,100%依赖客户端资源
  175. const clientProgress = estimatedTotal > 0 ?
  176. Math.min(resourcesCompleted / estimatedTotal, 1.0) : 0;
  177. totalProgress = clientProgress * 100;
  178. console.log(\`Client-only mode: \${resourcesCompleted}/\${estimatedTotal} resources\`);
  179. } else {
  180. // 有服务端编译活动,使用混合权重
  181. const serverWeight = serverProgress < 1.0 ? 0.6 : 0.3;
  182. const clientWeight = serverProgress < 1.0 ? 0.4 : 0.7;
  183. const serverPart = serverProgress * serverWeight;
  184. const clientPart = estimatedTotal > 0 ?
  185. Math.min(resourcesCompleted / estimatedTotal, 1.0) * clientWeight : 0;
  186. totalProgress = (serverPart + clientPart) * 100;
  187. console.log(\`Mixed mode: Server \${Math.round(serverProgress * 100)}%, Client \${resourcesCompleted}/\${estimatedTotal}\`);
  188. }
  189. // 确保进度不会倒退
  190. const currentWidth = parseFloat(progressBar.style.width) || 0;
  191. totalProgress = Math.max(totalProgress, currentWidth);
  192. // 更新进度条
  193. progressBar.style.width = Math.min(totalProgress, 100) + '%';
  194. // 更新状态显示
  195. statusDisplay.style.display = 'block';
  196. const mode = hasServerActivity ? 'Mixed' : 'Client-only';
  197. statusDisplay.textContent =
  198. \`Loading... \${Math.round(totalProgress)}% (\${mode}: \${resourcesCompleted}/\${estimatedTotal})\`;
  199. console.log(\`Progress: Total \${Math.round(totalProgress)}%\`);
  200. // 如果接近完成,开始检测完成状态
  201. if (totalProgress >= 85) {
  202. if (completionTimer) clearTimeout(completionTimer);
  203. completionTimer = setTimeout(checkCompletion, 800);
  204. }
  205. }
  206. // 监听服务端编译进度
  207. import.meta.hot.on('progress:update', (data) => {
  208. detectServerActivity();
  209. serverProgress = data.total > 0 ? data.processed / data.total : 0;
  210. updateProgress();
  211. });
  212. // 使用 PerformanceObserver 监控资源加载完成
  213. if (window.PerformanceObserver) {
  214. const completedResources = new Set();
  215. const observer = new PerformanceObserver((list) => {
  216. for (const entry of list.getEntries()) {
  217. if (entry.entryType === 'resource') {
  218. const isRelevantResource =
  219. entry.initiatorType === 'script' ||
  220. entry.initiatorType === 'link' ||
  221. entry.initiatorType === 'css' ||
  222. entry.name.includes('.js') ||
  223. entry.name.includes('.css') ||
  224. entry.name.includes('.ts');
  225. if (isRelevantResource && !completedResources.has(entry.name)) {
  226. completedResources.add(entry.name);
  227. resourcesCompleted++;
  228. lastResourceTime = Date.now();
  229. // 更保守的总数调整策略
  230. if (resourcesCompleted > estimatedTotal * 0.95) {
  231. estimatedTotal = Math.max(estimatedTotal, resourcesCompleted + 1);
  232. }
  233. console.log(\`Resource completed: \${entry.name} (type: \${entry.initiatorType})\`);
  234. updateProgress();
  235. }
  236. }
  237. }
  238. });
  239. observer.observe({ entryTypes: ['resource'] });
  240. }
  241. // 初始化
  242. function initialize() {
  243. estimatedTotal = estimateResourceCount();
  244. lastResourceTime = Date.now();
  245. console.log(\`Estimated total resources: \${estimatedTotal}\`);
  246. // 显示初始状态
  247. if (statusDisplay) {
  248. statusDisplay.style.display = 'block';
  249. statusDisplay.textContent = \`Initializing... (0/\${estimatedTotal} resources)\`;
  250. }
  251. updateProgress();
  252. // 启动服务端活动检测
  253. setTimeout(() => {
  254. if (!hasServerActivity) {
  255. console.log('No server activity detected, switching to client-only mode');
  256. updateProgress();
  257. }
  258. }, 1000);
  259. }
  260. // 页面加载完成后的处理
  261. function handlePageLoad() {
  262. setTimeout(() => {
  263. if (resourcesCompleted > 0) {
  264. estimatedTotal = Math.max(resourcesCompleted + 1, estimatedTotal);
  265. console.log(\`Final estimated total: \${estimatedTotal}\`);
  266. }
  267. updateProgress();
  268. // 页面加载完成后,更积极地检测完成状态
  269. setTimeout(() => {
  270. if (isLoading && resourcesCompleted >= estimatedTotal * 0.8) {
  271. console.log('Page load complete, forcing finish');
  272. forceComplete();
  273. }
  274. }, 1000);
  275. }, 500);
  276. }
  277. // 根据文档状态初始化
  278. if (document.readyState === 'loading') {
  279. document.addEventListener('DOMContentLoaded', initialize);
  280. document.addEventListener('load', handlePageLoad);
  281. } else {
  282. setTimeout(initialize, 0);
  283. if (document.readyState === 'complete') {
  284. setTimeout(handlePageLoad, 100);
  285. } else {
  286. document.addEventListener('load', handlePageLoad);
  287. }
  288. }
  289. // HMR 更新时重置状态
  290. import.meta.hot.on('vite:beforeUpdate', () => {
  291. console.log('HMR update detected, maintaining progress tracking...');
  292. });
  293. }
  294. `,
  295. injectTo: 'body'
  296. }
  297. ]
  298. }
  299. }
  300. }
  301. }
  302. }