-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
211 lines (195 loc) · 6.97 KB
/
vite.config.ts
File metadata and controls
211 lines (195 loc) · 6.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import type { Plugin } from 'vite'
/**
* 开发模式代理插件
* 在 vite dev server 中提供 /proxy 和 /api/services 接口
* 与 cli/server.js 的行为一致
*/
function devProxyPlugin(): Plugin {
return {
name: 'dev-proxy',
configureServer(server) {
// 代理模式检测
server.middlewares.use('/api/services', (_req, res) => {
res.setHeader('Content-Type', 'application/json')
res.end('[]')
})
// 代理:获取远端 openapi.json
server.middlewares.use('/proxy', async (req, res, next) => {
if (req.method !== 'GET') return next()
const url = new URL(req.url || '', 'http://localhost')
const targetUrl = url.searchParams.get('url')
if (!targetUrl) {
res.statusCode = 400
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: '缺少 url 参数' }))
return
}
try {
const headers: Record<string, string> = { Accept: 'application/json' }
const customAuth = req.headers['x-custom-auth']
if (customAuth) {
headers['Authorization'] = Array.isArray(customAuth) ? customAuth[0] : customAuth
}
let resp = await fetch(targetUrl, { headers, redirect: 'follow' })
// 如果返回的是 HTML(可能是 Swagger UI 页面),尝试常见的 JSON 端点
const contentType = resp.headers.get('content-type') || ''
if (resp.ok && contentType.includes('text/html')) {
const baseUrl = new URL(targetUrl)
const fallbackPaths = [
'/openapi.json',
'/v3/api-docs',
'/swagger.json',
'/api-docs.json',
]
for (const path of fallbackPaths) {
const fallbackUrl = `${baseUrl.origin}${path}`
if (fallbackUrl === targetUrl) continue
const fallbackResp = await fetch(fallbackUrl, { headers })
const fallbackCt = fallbackResp.headers.get('content-type') || ''
if (fallbackResp.ok && fallbackCt.includes('application/json')) {
resp = fallbackResp
break
}
}
}
if (!resp.ok) {
res.statusCode = resp.status
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: `远端返回 ${resp.status}: ${resp.statusText}` }))
return
}
const respContentType = resp.headers.get('content-type') || 'application/json'
res.setHeader('Content-Type', respContentType)
res.end(await resp.text())
} catch (err: any) {
res.statusCode = 502
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: `代理请求失败: ${err.message}` }))
}
})
// 代理:转发 API 调试请求
server.middlewares.use('/proxy/api', async (req, res, next) => {
if (req.method !== 'POST') return next()
const chunks: Buffer[] = []
req.on('data', (c) => chunks.push(c))
req.on('end', async () => {
try {
const body = JSON.parse(Buffer.concat(chunks).toString())
if (!body || !body.url) {
res.statusCode = 400
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: '缺少 url' }))
return
}
const fetchOptions: RequestInit = {
method: body.method || 'GET',
headers: body.headers || {},
}
if (body.body && !['GET', 'HEAD'].includes((fetchOptions.method as string).toUpperCase())) {
fetchOptions.body = typeof body.body === 'string' ? body.body : JSON.stringify(body.body)
}
const resp = await fetch(body.url, fetchOptions)
const responseHeaders: Record<string, string> = {}
resp.headers.forEach((value, key) => { responseHeaders[key] = value })
// 特殊处理 set-cookie:多个值用 \n 分隔保留完整信息
const setCookies = resp.headers.getSetCookie?.() || []
if (setCookies.length > 1) {
responseHeaders['set-cookie'] = setCookies.join(', ')
}
const contentType = responseHeaders['content-type'] || ''
// 二进制图片用 base64 编码传输,避免 text() 损坏数据
const isBinaryImage = contentType.startsWith('image/') && !contentType.includes('svg')
let responseBody: string
let bodyEncoding: string | undefined
if (isBinaryImage) {
const buffer = Buffer.from(await resp.arrayBuffer())
responseBody = buffer.toString('base64')
bodyEncoding = 'base64'
} else {
responseBody = await resp.text()
}
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({
status: resp.status,
statusText: resp.statusText,
headers: responseHeaders,
body: responseBody,
bodyEncoding,
}))
} catch (err: any) {
res.statusCode = 502
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: `API 代理请求失败: ${err.message}` }))
}
})
})
},
}
}
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: {
hoistStatic: true,
cacheHandlers: true,
},
},
}),
devProxyPlugin(),
],
server: {
port: 5200,
},
build: {
outDir: 'dist',
emptyOutDir: true,
cssCodeSplit: true,
chunkSizeWarningLimit: 1000,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
debugger: resolve(__dirname, 'debugger.html'),
},
output: {
manualChunks: {
'vue-vendor': ['vue'],
'antd-vendor': ['ant-design-vue', '@ant-design/icons-vue'],
'codemirror-vendor': [
'codemirror',
'@codemirror/lang-json',
'@codemirror/lang-html',
'@codemirror/lang-xml',
'@codemirror/view',
'@codemirror/state',
'@codemirror/language',
'@codemirror/theme-one-dark',
],
'utils-vendor': ['marked'],
},
entryFileNames: 'assets/[name]-[hash].js',
chunkFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash].[ext]',
},
},
},
optimizeDeps: {
include: [
'vue',
'ant-design-vue',
'@ant-design/icons-vue',
'marked',
'codemirror',
],
},
})