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

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver, VantResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
import inject from '@rollup/plugin-inject';

// https://vite.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    base: env.VITE_API_ROUTE_URL,
    optimizeDeps: {
      include: ['jquery']
      // exclude: [
      //   'modernizr',
      //   'src/assets/js/modernizr.2.5.3.min.js'
      // ]
    },
    // build: {
    //   rollupOptions: {
    //     external: [
    //       /modernizr/,
    //       /requirejs/
    //     ]
    //   }
    // },
    plugins: [
      vue(),
      vueDevTools(),
      AutoImport({
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: ['vue', 'vue-router', 'pinia'],
        // 自动导入 Element Plus 相关函数
        resolvers: [ElementPlusResolver(), VantResolver()],
        // 生成自动导入的TS声明文件
        dts: 'src/auto-imports.d.ts',
      }),
      Components({
        // 自动导入组件
        resolvers: [ElementPlusResolver(), VantResolver()],
        // 生成自动导入的TS声明文件
        dts: 'src/components.d.ts',
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')], // SVG 存放路径
        symbolId: 'icon-[name]'
      }),
      inject({
        $: 'jquery',
        jQuery: 'jquery',
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    server: {
      proxy: {
        '/api': {
          target: 'http://222.85.214.245:9666',
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_API_BASE_URL), '/api'),
          bypass(req, res, options) {
            const realUrl = options.target + (options.rewrite ? options.rewrite(req.url) : '');
            console.log(realUrl); // 在终端显示
            res.setHeader('A-Real-Url', realUrl); // 添加响应标头(A-Real-Url为自定义命名)，在浏览器中显示
          },
        }
      },
      host: '0.0.0.0',
      port: 8089,
    }
  }
})
