Skip to content

Vite 7 外掛開發與建構最佳化策略

Vite 已經成為前端建構工具的事實標準。2026 年的 Vite 7 不僅提升了建構速度,還增強了外掛系統的能力,讓開發者可以更精細地控制建構過程。

外掛基礎

Vite 外掛遵循 Rollup 外掛規範,同時擴展了開發伺服器的能力:

typescript
import type { Plugin } from 'vite';

export default function myPlugin(): Plugin {
  return {
    name: 'my-plugin',
    
    // 開發伺服器鉤子
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        if (req.url === '/api/hello') {
          res.setHeader('Content-Type', 'application/json');
          res.end(JSON.stringify({ message: 'Hello from plugin' }));
        } else {
          next();
        }
      });
    },
    
    // 建構鉤子
    transform(code, id) {
      if (id.endsWith('.custom')) {
        return `export default ${JSON.stringify(code)}`;
      }
      return null;
    }
  };
}

常見外掛模式

模式 1:檔案轉換

typescript
function yamlPlugin(): Plugin {
  return {
    name: 'yaml-loader',
    transform(code, id) {
      if (id.endsWith('.yaml') || id.endsWith('.yml')) {
        const parsed = yaml.load(code);
        return `export default ${JSON.stringify(parsed)}`;
      }
      return null;
    }
  };
}

模式 2:虛擬模組

typescript
function envPlugin(): Plugin {
  return {
    name: 'env-virtual',
    resolveId(id) {
      if (id === 'virtual:env') {
        return '\0virtual:env';
      }
    },
    load(id) {
      if (id === '\0virtual:env') {
        const env = {
          API_URL: process.env.API_URL,
          NODE_ENV: process.env.NODE_ENV
        };
        return `export default ${JSON.stringify(env)}`;
      }
    }
  };
}

建構最佳化策略

策略 1:程式碼分割

typescript
// vite.config.ts
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue', 'vue-router'],
          ui: ['element-plus', '@element-plus/icons-vue']
        }
      }
    }
  }
});

開發伺服器最佳化

typescript
export default defineConfig({
  server: {
    fs: { allow: ['..'] },
    optimizeDeps: {
      include: ['vue', 'vue-router'],
      exclude: ['your-local-package']
    },
    hmr: { overlay: true }
  }
});

外掛除錯

typescript
function debugPlugin(): Plugin {
  return {
    name: 'debug-plugin',
    buildStart() { console.log('[debug] buildStart'); },
    resolveId(source, importer) { console.log('[debug] resolveId', source, importer); },
    load(id) { console.log('[debug] load', id); },
    transform(code, id) { console.log('[debug] transform', id); }
  };
}

小結

Vite 7 的外掛系統提供了強大的擴展能力。外掛可以轉換檔案、提供虛擬模組、增強 HMR 和最佳化建構過程。2026 年的 Vite 外掛開發原則:保持簡單、測試覆蓋、效能優先。好的外掛應該是無侵入的、可組合的、易於除錯的。

MIT Licensed