/*
 * @Descripttion:
 * @Author: zenghua.wang
 * @Date: 2022-09-18 21:24:29
 * @LastEditors: zenghua.wang
 * @LastEditTime: 2025-04-18 15:41:11
 */

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
// import qiankun from 'vite-plugin-qiankun';
import eslintPlugin from 'vite-plugin-eslint';
import vueSetupExtend from 'vite-plugin-vue-setup-extend';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import compression from 'vite-plugin-compression';
import { viteMockServe } from 'vite-plugin-mock';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import postcssImport from 'postcss-import';
import autoprefixer from 'autoprefixer';
import { resolve } from 'path';

const useDevMode = true;

export default defineConfig(({ command, mode }) => {
  const { VITE_PORT, VITE_APP_NAME, VITE_APP_BASE_API, VITE_APP_BASE_URL } = loadEnv(mode, process.cwd());
  const config = {
    base: '/',
    build: {
      target: 'ESNext',
      outDir: 'dist',
      minify: 'terser',
    },
    server: {
      host: '0.0.0.0',
      port: VITE_PORT,
      open: true,
      https: false,
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
      proxy: {
        [VITE_APP_BASE_API]: {
          target: VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/apis/, ''),
        },
      },
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
      extensions: ['.js', '.vue', '.json', '.ts'],
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/global.scss";',
          api: 'modern-compiler',
        },
      },
      postcss: {
        plugins: [
          postcssImport,
          autoprefixer({
            overrideBrowserslist: ['> 1%', 'last 2 versions'],
          }),
        ],
      },
    },
    plugins: [
      vue(),
      // qiankun(VITE_APP_NAME, { useDevMode }),
      vueSetupExtend(),
      eslintPlugin({
        include: ['src/**/*.ts', 'src/**/*.vue', 'src/*.ts', 'src/*.vue'],
      }),
      Components({
        dirs: ['src/components'],
        extensions: ['vue', 'js', 'jsx', 'ts', 'tsx'],
        resolvers: [],
      }),
      compression(),
      AutoImport({
        include: [/\.[tj]s?$/, /\.vue$/],
        imports: ['vue', 'vue-router'],
      }),
      createSvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), 'src/assets/svgs')],
        symbolId: 'icon-[name]',
      }),
      viteMockServe({
        mockPath: 'src/mock',
        watchFiles: true,
        localEnabled: command === 'dev',
        prodEnabled: false,
      }),
    ],
  };
  if (mode === 'production') {
    config.build.terserOptions = {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    };
  }
  return config;
});
