import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import UnoCSS from 'unocss/vite'
import config from './src/config'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig({
    resolve: {
        alias: {
            '~src': `${resolve(__dirname, './src')}`,
            '~com': `${resolve(__dirname, './src/components')}`,
            '~api': resolve(__dirname, './src/api/modules'),
        },
    },
    plugins: [
        vue(),
        UnoCSS(),
        AutoImport({
            resolvers: [ElementPlusResolver()],
        }),
        Components({
            resolvers: [ElementPlusResolver()],
        }),
    ],
    build: {
        rollupOptions: {
            output: {
                manualChunks(id) {
                    let libStr = '@vue,element-plus,echarts,vue-router,pinia,js-fast-way'
                    const libs = libStr.split(',')
                    if (id.includes('node_modules')) {
                        const arr = id.toString().split('node_modules/')[1].split('/')
                        if (libs.indexOf(arr[0]) !== -1) {
                            return '_' + arr[0]
                        } else {
                            return '__vendor'
                        }
                    }
                },
                chunkFileNames: 'static/js1/[name]-[hash].js',
                entryFileNames: 'static/js2/[name]-[hash].js',
                assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
            },
            brotliSize: false, // 不统计
            target: 'esnext',
            minify: 'esbuild', // 混淆器，terser构建后文件体积更小
        },
    },
    server: {
        ...config.vite,
        proxy: {
            '/api': {
                ws: true,
                changeOrigin: true,
                target: config.target,
                rewrite: (path) => path.replace(new RegExp('^/api'), '/'),
            },
        },
    },
})
