import {
  defineConfig,
  loadEnv
} from 'vite'
import {
  resolve
} from 'path'
import libConfig from './lib.config';
import createVitePlugins from './vite/plugins'
// https://vitejs.dev/config/
export default ({
  mode,
  command
}) => {
  const env = loadEnv(mode, process.cwd())
  const {
    VITE_APP_BASE,
    VITE_APP_ENV
  } = env
  // 判断是打生产环境包
  const isProd = VITE_APP_ENV === 'production'
  return defineConfig({
    base: VITE_APP_BASE,
    define: {
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    },
    build: {
      minify: 'esbuild',  // 使用 esbuild 进行压缩，默认是这个选项
      esbuild: {
        // 进一步定制压缩选项
        drop: ['console', 'debugger'], // 删除 console 和 debugger 语句
        minifyWhitespace: true,         // 删除空白字符
        minifySyntax: true,            // 删除多余的语法
        minifyIdentifiers: true,       // 压缩变量名
      },
      rollupOptions: {
        // input: {
        //   main: resolve(__dirname, 'index.html'), // 指定 index.html 为入口
        //   iot: resolve(__dirname, 'iot.html'), // 指定 iot.html 为入口
        // },
        output: {
          compact: true,
          manualChunks: {
            'element-plus': ['element-plus'],
            'avue': ['@smallwei/avue'],
            'vue-3d-model': ['vue-3d-model'],
            'monaco-editor': ['monaco-editor'],
            'vuedraggable': ['vuedraggable']
          },
        }
      }
    },
    ...(() => {
      if (VITE_APP_ENV == 'lib') {
        return libConfig
      }
      return {}
    })(),
    optimizeDeps: {
      esbuildOptions: {
        target: 'esnext',
      },
    },
    server: {
      port: 5333,
      // proxy: {
      //   '/api': {
      //     target: 'https://data.avuejs.com/api/',
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/api/, '')
      //   }
      // }
    },
    resolve: {
      alias: {
        'vue': 'vue/dist/vue.esm-bundler.js',
        '~': resolve(__dirname, './'),
        "@": resolve(__dirname, "./src"),
        "components": resolve(__dirname, "./src/components"),
        "styles": resolve(__dirname, "./src/styles"),
        "utils": resolve(__dirname, "./src/utils"),
      }
    },
    plugins: createVitePlugins(env, command === 'build')
  })
}