正在加载,请稍候…

Vite 构建工具:配置与性能优化

优化 Vite 配置以加快开发和生产构建速度,学习代码分割、分块策略、插件及性能调优。

Vite 构建工具:配置与性能优化

Vite 构建工具:配置与性能优化

Vite 在开发时使用原生 ES 模块,生产构建时使用 Rollup。

基本配置

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@components': path.resolve(__dirname, './src/components'),
    },
  },
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
});

Vite 构建工具:配置与性能优化 插图

构建优化

export default defineConfig({
  build: {
    // 块大小警告阈值
    chunkSizeWarningLimit: 1000,

    // 用于代码分割的 Rollup 选项
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom'],
          ui: ['@mui/material', '@emotion/react'],
        },
        // 动态块命名
        chunkFileNames: 'assets/[name]-[hash].js',
        entryFileNames: 'assets/[name]-[hash].js',
        assetFileNames: 'assets/[name]-[hash].[ext]',
      },
    },

    // 压缩选项
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },

    // 源码映射
    sourcemap: false,

    // 目标现代浏览器
    target: 'es2020',
  },
});

Vite 构建工具:配置与性能优化 插图

环境变量

// vite.config.ts
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    define: {
      __APP_VERSION__: JSON.stringify(env.npm_package_version),
    },
  };
});
# .env.development
VITE_API_URL=http://localhost:8080
VITE_DEBUG=true

# .env.production
VITE_API_URL=https://api.myapp.com
VITE_DEBUG=false
// 在代码中使用
const apiUrl = import.meta.env.VITE_API_URL;

Vite 构建工具:配置与性能优化 插图

性能插件

import { visualizer } from 'rollup-plugin-visualizer';
import viteCompression from 'vite-plugin-compression';
import { splitVendorChunkPlugin } from 'vite';

export default defineConfig({
  plugins: [
    react(),
    splitVendorChunkPlugin(),
    viteCompression({ algorithm: 'gzip' }),
    visualizer({
      filename: 'dist/stats.html',
      open: true,
      gzipSize: true,
    }),
  ],
});

SSR 配置

export default defineConfig({
  ssr: {
    noExternal: ['@some/package'],
    external: ['fs', 'path'],
  },
});

开发服务器性能

export default defineConfig({
  optimizeDeps: {
    include: ['react', 'react-dom', 'lodash-es'],
    exclude: ['@local/package'],
    esbuildOptions: {
      target: 'es2020',
    },
  },
  server: {
    warmup: {
      clientFiles: ['./src/components/*.tsx'],
    },
  },
});

合理的 Vite 配置可以将构建时间比 Webpack 减少 10 倍。