import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path" // 需安装此模块
import { fileURLToPath, URL } from 'node:url'

// https://vite.dev/config/
export default defineConfig(({mode}) => {
  const ENV = loadEnv(mode, process.cwd())
  return {
    base: './',  // 基础路径配置
    plugins: [vue()],
    resolve: {
      alias: {
        // 这里就是需要配置resolve里的别名
        "@": fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    build: {
      outDir: 'dist',
      assetsInlineLimit: 4096, // 小于4kb的资源将被内联为base64
      emptyOutDir: true, // 构建前清空输出目录
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['vue', 'vue-router', 'pinia'],
            ui: ['element-plus', '@element-plus/icons-vue']
          },
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            const info = assetInfo.name.split('.');
            let extType = info[info.length - 1];
            if (/\.(png|jpe?g|gif|svg|webp|ico)(\?.*)?$/.test(assetInfo.name)) {
              extType = 'img';
            } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
              extType = 'fonts';
            } else if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/.test(assetInfo.name)) {
              extType = 'media';
            }
            return `static/${extType}/[name]-[hash][extname]`;
          }
        }
      },
      // 确保 assets 目录下的资源被复制到构建目录
      assetsDir: 'static',
      copyPublicDir: true
    },
    server: {
      host: '0.0.0.0', // 指定服务器主机名
      port: 3000, // 指定服务器端口
      proxy: {
        [ENV.VITE_APP_BASE_API5]: {
          target: 'https://screen.bmetech.com',  // 更新为完整的基础路径
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')  // 添加路径重写规则
        },
      }
    }
  }
})
