import { defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
// import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import path from 'path'
const pathSrc = path.resolve(__dirname, 'src')

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  // console.log('xxxx', env.VITE_APP_BASE_PRE)

  const { VITE_APP_BASE_URL, VITE_APP_BASE_PRE, VITE_APP_BASE_URLpro } = env
  console.log('VITE_APP_BASE_URL', VITE_APP_BASE_URL, VITE_APP_BASE_PRE)
  return {
    transpileDependencies: ['uview-plus'],
    plugins: [
      uni(),
      AutoImport({
        imports: ['vue', 'uni-app'],
        // 生成自动导入的TS声明文件
        vueTemplate: true,
        dts: path.resolve(pathSrc, 'types', 'auto-imports.d.ts')
      })
      // Components({
      //     dts: path.resolve(pathSrc, 'types', 'auto-components.d.ts')
      // })
      // Components({
      //     dts: './src/types/auto-components.d.ts',
      //     dirs: [path.resolve(__dirname, './src/components')],
      // }),
    ],
    build: {
      target: 'es2020' // 或 'esnext'（使用最新 ES 特性）
    },
    resolve: {
      // 别名
      alias: {
        '@': path.join(__dirname, './src')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          silenceDeprecations: ['import'],
          // additionalData: `@import "uview-plus/theme.scss";`, //如果还是报scss 错 查看下路径
          api: 'modern-compiler' // 或 "modern"
          // // 若需兼容旧语法，可保留以下配置
          // legacy: true
        }
      }
    },
    // css: {
    //     preprocessorOptions: {
    //         scss: {
    //             additionalData: '@import "./src/uni.scss";'
    //         }
    //     }
    // },
    server: {
      // port: 3000,
      proxy: {
        [VITE_APP_BASE_PRE]: {
          target: VITE_APP_BASE_URL + ':' + VITE_APP_BASE_URLpro,
          ws: true,
          changeOrigin: true
          // 要记得加rewrite这句
          // rewrite: (path) => path.replace(/^\/apis/, ''),
          // rewrite: (path) => path.replace(new RegExp('^' + VITE_APP_BASE_PRE), '')
        }
      }
    }
  }
})
