import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import qiankun from 'vite-plugin-qiankun'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const chunkName = ['lodash-es', 'element-plus', '@form-create/designer']
  // 根据环境变量设置 base
  const base = mode === 'release' ? '/saas/form/' : '/'
  return {
    plugins: [
      vue(),
      vueJsx(),
      qiankun('curstom-form', {
        useDevMode: true, // 开发模式下使用热更新
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      port: 5173,
      cors: true,
    },
    base,
    build: {
      target: 'esnext',
      outDir: 'form',
      chunkSizeWarningLimit: 1000,
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          assetFileNames: 'static/[name].[hash].[ext]', // 确保静态资源路径正确
          chunkFileNames: () => {
            return 'static/[name].[hash].js'
          },
          entryFileNames: 'static/[name].[hash].js',
          manualChunks(id: string) {
            if (id.includes('node_modules')) {
              const name = chunkName.find((item) => id.includes(item))
              if (name) return name
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          },
        },
      },
    },
  }
})
