基础项目打包配置


import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path';
import AutoImport from 'unplugin-auto-import/vite'



// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV, VITE_APP_BASE_URL } = env
  console.info(VITE_APP_ENV)
  return {
    plugins: [
      vue(),
      AutoImport({
        imports: [
          'vue',
          'vue-router',
          'pinia'
        ]
      })
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      }
    },
    define: {
      // 根据当前模式(mode)为变量赋值
      PROD: mode === 'production',  // 生产环境:true
      DEV: mode === 'development',  // 开发环境:true
      TEST: mode === 'test'         // 测试环境:true
    },
    server: {
      host: true,
      port: 5173,
      open: true,
      cors: true,
      proxy: {
        '/api': {
          target: VITE_APP_BASE_URL, // 后端服务地址
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
        '/auth': {
          target: VITE_APP_BASE_URL,
          changeOrigin: true,
          secure: false
        }
      }
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      assetsDir: 'assets',
      minify: 'esbuild',
      rollupOptions: {
        output: {
          // 分包策略
          manualChunks: {
            // 将Vue相关库打包到vendor
            vendor: ['vue', 'vue-router', 'pinia'],
            // 将Element Plus打包到element
            element: ['element-plus'],
            // 将工具库打包到utils
            utils: ['axios', 'js-cookie']
          },
          // 文件名配置
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      },
      // 启用CSS代码分割
      cssCodeSplit: true,
      // 启用源码映射(生产环境建议关闭)
      sourcemap: false,
      // 设置chunk大小警告的限制
      chunkSizeWarningLimit: 1000
    },
    // 预构建优化
    optimizeDeps: {
      include: ['vue', 'vue-router', 'pinia', 'element-plus', 'axios'],
      exclude: []
    },
    // CSS配置
    css: {
      preprocessorOptions: {
        scss: {
          // 移除additionalData,避免与组件中的@import冲突
        }
      }
    }
  }
})

posted @ 2025-08-04 15:03  OvOGhostFace  阅读(10)  评论(0)    收藏  举报