import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

export default defineConfig({
  plugins: [
    vue(),
    // 开发时将 ../data 目录挂载到 /data 路径
    {
      name: 'serve-data-dir',
      configureServer(server) {
        server.middlewares.use('/data', (req, res, next) => {
          const filePath = path.resolve(__dirname, '../data', req.url.replace(/^\//, '').split('?')[0])
          try {
            const content = fs.readFileSync(filePath, 'utf-8')
            res.setHeader('Content-Type', 'application/json; charset=utf-8')
            res.end(content)
          } catch {
            next()
          }
        })
      }
    }
  ],
  server: {
    port: 5173
  },
  build: {
    outDir: resolve(__dirname, '../dist')
  }
})
