Skip to content

Instantly share code, notes, and snippets.

@aziis98
Created June 30, 2022 00:13
Show Gist options
  • Save aziis98/e6c99222112b7201c2ea5d75725d87b0 to your computer and use it in GitHub Desktop.
Save aziis98/e6c99222112b7201c2ea5d75725d87b0 to your computer and use it in GitHub Desktop.
Simple ViteJS dev server with custom dynamic routes
import { dirname, resolve } from 'path'
import express from 'express'
import { createServer as createViteServer } from 'vite'
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url))
const ROUTES = {
'/': './index.html',
'/buckets/:bucket': './[bucket].html',
}
async function createServer() {
const app = express()
// In middleware mode, if you want to use Vite's own HTML serving logic
// use `'html'` as the `middlewareMode` (ref https://vitejs.dev/config/#server-middlewaremode)
const vite = await createViteServer({
server: { middlewareMode: 'html' },
})
for (const [route, file] of Object.entries(ROUTES)) {
app.get(route, (req, res) => {
const filePath = resolve(__dirname, file)
console.log(`Custom Route: %s`, req.url)
return res.sendFile(filePath)
})
}
app.use(vite.middlewares)
app.listen(3000)
}
createServer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment