import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import fs from 'fs' import path from 'path' import type { Plugin } from 'vite' // 配置文件路径 const CONFIG_FILE = path.resolve(__dirname, 'config.json') // 自定义插件:处理配置文件的读写 function configApiPlugin(): Plugin { return { name: 'config-api', configureServer(server) { // 读取配置 server.middlewares.use('/api/config', (req, res, next) => { if (req.method === 'GET') { try { if (fs.existsSync(CONFIG_FILE)) { const config = fs.readFileSync(CONFIG_FILE, 'utf-8') res.setHeader('Content-Type', 'application/json') res.end(config) } else { res.statusCode = 404 res.end(JSON.stringify({ error: 'Config not found' })) } } catch (error) { res.statusCode = 500 res.end(JSON.stringify({ error: 'Failed to read config' })) } } else if (req.method === 'POST') { let body = '' req.on('data', (chunk) => { body += chunk.toString() }) req.on('end', () => { try { const config = JSON.parse(body) fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2)) res.setHeader('Content-Type', 'application/json') res.end(JSON.stringify({ success: true })) } catch (error) { res.statusCode = 500 res.end(JSON.stringify({ error: 'Failed to save config' })) } }) } else { next() } }) } } } // https://vite.dev/config/ export default defineConfig({ plugins: [vue(), configApiPlugin()], })