vite-plugin-compile-progress.js 15 KB

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