Created
June 30, 2022 00:13
-
-
Save aziis98/e6c99222112b7201c2ea5d75725d87b0 to your computer and use it in GitHub Desktop.
Simple ViteJS dev server with custom dynamic routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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