64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
|
|
import { existsSync, readFileSync } from 'node:fs'
|
||
|
|
import { resolve } from 'node:path'
|
||
|
|
import { defineConfig, type Plugin } from 'vite'
|
||
|
|
import react from '@vitejs/plugin-react'
|
||
|
|
|
||
|
|
function serveBuiltDocs(): Plugin {
|
||
|
|
return {
|
||
|
|
name: 'serve-built-docs',
|
||
|
|
configureServer(server) {
|
||
|
|
const publicDir = resolve('public')
|
||
|
|
|
||
|
|
server.middlewares.use((req, res, next) => {
|
||
|
|
const url = req.url?.split('?')[0]
|
||
|
|
if (!url) return next()
|
||
|
|
|
||
|
|
const filePath = resolve(publicDir, url.slice(1))
|
||
|
|
|
||
|
|
if ((url.endsWith('.txt') || url.endsWith('.md')) && existsSync(filePath)) {
|
||
|
|
res.setHeader(
|
||
|
|
'Content-Type',
|
||
|
|
url.endsWith('.md')
|
||
|
|
? 'text/markdown; charset=utf-8'
|
||
|
|
: 'text/plain; charset=utf-8',
|
||
|
|
)
|
||
|
|
res.end(readFileSync(filePath))
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
const [, site] = url.split('/')
|
||
|
|
if (!site || site.includes('.')) return next()
|
||
|
|
|
||
|
|
const siteDir = resolve(publicDir, site)
|
||
|
|
if (!existsSync(resolve(siteDir, 'index.html'))) return next()
|
||
|
|
|
||
|
|
if (url === `/${site}`) {
|
||
|
|
req.url = `/${site}/index.html`
|
||
|
|
return next()
|
||
|
|
}
|
||
|
|
|
||
|
|
if (url.endsWith('/')) {
|
||
|
|
if (existsSync(resolve(filePath, 'index.html'))) {
|
||
|
|
req.url = `${url}index.html`
|
||
|
|
return next()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!url.split('/').pop()?.includes('.')) {
|
||
|
|
if (existsSync(`${filePath}.html`)) {
|
||
|
|
req.url = `${url}.html`
|
||
|
|
return next()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
next()
|
||
|
|
})
|
||
|
|
},
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// https://vite.dev/config/
|
||
|
|
export default defineConfig({
|
||
|
|
plugins: [react(), serveBuiltDocs()],
|
||
|
|
})
|