39 lines
1.8 KiB
TypeScript
39 lines
1.8 KiB
TypeScript
import { defineConfig, mergeConfig, type Plugin } from 'vite'
|
|
import baseConfig from '../vite.config'
|
|
import { createHomeFixture, fixtureBootstrap, previewPage } from './home-fixtures'
|
|
|
|
// This config is opt-in and is never loaded by the WeChat production build.
|
|
const fixtures: Plugin = {
|
|
name: 'home-design-preview',
|
|
transformIndexHtml(html, context) {
|
|
const scenario = new URL(context.originalUrl || '/', 'http://localhost').searchParams.get('homeFixture')
|
|
if (!scenario) return html
|
|
return { html, tags: [{ tag: 'script', children: fixtureBootstrap(scenario), injectTo: 'head-prepend' }] }
|
|
},
|
|
configureServer(server) {
|
|
const requests = new Map<string, number>()
|
|
server.middlewares.use((req, res, next) => {
|
|
const url = new URL(req.url || '/', 'http://localhost')
|
|
if (url.pathname === '/__home-preview') {
|
|
res.setHeader('Content-Type', 'text/html; charset=utf-8')
|
|
res.end(previewPage)
|
|
return
|
|
}
|
|
if (url.pathname !== '/__home-fixture-api') return next()
|
|
const scenario = url.searchParams.get('scenario') || 'guest'
|
|
const path = url.searchParams.get('path') || ''
|
|
const key = `${url.searchParams.get('instance')}:${path}`
|
|
const count = (requests.get(key) || 0) + 1
|
|
requests.set(key, count)
|
|
const result = createHomeFixture(scenario, path, count)
|
|
const respond = () => {
|
|
res.statusCode = result.status || 200
|
|
res.setHeader('Content-Type', 'application/json; charset=utf-8')
|
|
res.end(JSON.stringify({ success: res.statusCode < 400, data: result.data, message: '预览中的模拟网络错误' }))
|
|
}
|
|
setTimeout(respond, scenario === 'loading' ? 5000 : 120)
|
|
})
|
|
},
|
|
}
|
|
export default mergeConfig(baseConfig, defineConfig({ plugins: [fixtures] }))
|