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

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  server: {
    host: '0.0.0.0',  // 允许局域网访问
    port: 5173
  },
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    },
    // 生成带hash的文件名，避免浏览器缓存
    rollupOptions: {
      output: {
        // 入口文件名
        entryFileNames: 'assets/js/[name].[hash].js',
        // 代码分割文件名
        chunkFileNames: 'assets/js/[name].[hash].js',
        // 资源文件名
        assetFileNames: (assetInfo) => {
          // 根据文件类型分目录存放
          if (assetInfo.name.endsWith('.css')) {
            return 'assets/css/[name].[hash].[ext]'
          }
          if (/\.(png|jpe?g|gif|svg|webp|ico)$/.test(assetInfo.name)) {
            return 'assets/images/[name].[hash].[ext]'
          }
          if (/\.(woff2?|eot|ttf|otf)$/.test(assetInfo.name)) {
            return 'assets/fonts/[name].[hash].[ext]'
          }
          return 'assets/[name].[hash].[ext]'
        }
      }
    }
  }
})