| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- export function progressTrackingPlugin() {
- let server
- const moduleStats = {
- total: 0,
- processed: 0,
- pending: new Set()
- }
-
- return {
- name: 'progress-tracking',
- apply: 'serve',
- enforce: 'pre',
- configureServer(_server) {
- server = _server
- },
- async transform(code, id) {
- if (server && id) {
- moduleStats.total++
- moduleStats.pending.add(id)
-
- // 发送进度更新到客户端
- server.ws.send('progress:update', {
- total: moduleStats.total,
- processed: moduleStats.processed,
- current: id
- })
-
- // 等待依赖处理完成
- await server.waitForRequestsIdle(id)
-
- moduleStats.processed++
- moduleStats.pending.delete(id)
-
- // 发送完成状态
- server.ws.send('progress:update', {
- total: moduleStats.total,
- processed: moduleStats.processed,
- current: null
- })
- }
- },
- transformIndexHtml: {
- order: 'pre', // 在 Vite 内部转换之前执行
- handler(html, ctx) {
- return {
- html,
- tags: [
- {
- tag: 'style',
- children: `
- #vite-progress-bar {
- position: fixed;
- top: 0;
- left: 0;
- width: 0%;
- height: 3px;
- background: #646cff;
- transition: width 0.3s;
- z-index: 9999;
- }
- `,
- injectTo: 'head'
- },
- {
- tag: 'div',
- attrs: { id: 'vite-progress-bar' },
- injectTo: 'body-prepend'
- },
- {
- tag: 'script',
- attrs: { type: 'module' }, // 关键:添加 type="module"
- children: `
- if (import.meta.hot) {
- import.meta.hot.on('progress:update', (data) => {
- const bar = document.getElementById('vite-progress-bar');
- if (bar) {
- const percentage = (data.processed / data.total) * 100;
- bar.style.width = percentage + '%';
- if (percentage >= 100) {
- setTimeout(() => bar.style.display = 'none', 1000);
- }
- }
- });
- }
- `,
- injectTo: 'body'
- }
- ]
- }
- }
- }
- }
- }
|