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

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  return {
    base: env.VITE_BASE_URL,
    plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:80',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '') //去掉 api
      }
    }
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    rollupOptions: {
      output: {
        format: 'es',
        manualChunks: {
          // Vue核心库
          vue: ['vue', 'pinia'],
          // UI组件库
          elementPlus: ['element-plus'],
          // Markdown编辑器相关
          markdownEditor: ['@kangc/v-md-editor', 'vditor'],
          // PDF生成工具
          pdfTools: ['jspdf', 'html2canvas'],
          // 代码高亮
          highlight: ['highlight.js'],
          // 代码编辑器
          codemirror: ['codemirror'],
          // Pinia状态管理
          piniaPlugin: ['pinia-plugin-persistedstate']
        },
        chunkFileNames: (chunkInfo) => {
          const facadeModuleId = chunkInfo.facadeModuleId || chunkInfo.moduleIds[0]
          if (facadeModuleId.includes('node_modules')) {
            return 'assets/js/vendor/[name]-[hash].js'
          }
          return 'assets/js/[name]-[hash].js'
        },
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          if (assetInfo.name.endsWith('.css')) {
            return 'assets/css/[name]-[hash].[ext]';
          }
          if (assetInfo.name.endsWith('.js')) {
            return 'assets/js/[name]-[hash].[ext]';
          }
          return 'assets/[name]-[hash].[ext]';
        },
      },
    },
    sourcemap: false,
    chunkSizeWarningLimit: 1000 // 设置为1MB
  }
}
})