import path from 'path' import fs from 'fs/promises' import { createServer as createViteServer } from 'vite' import express from 'express' import { createApiRouter } from './server/routers.js' const config = { isDevelopment: process.env.MODE === 'development', port: process.env.PORT || 3000, } console.dir(config) async function createDevRouter() { const r = express.Router() const vite = await createViteServer({ server: { middlewareMode: true }, appType: 'custom', }) r.use(vite.middlewares) r.use('*', async (req, res, next) => { try { const indexHtml = await fs.readFile(path.resolve('./index.html'), 'utf-8') const transformedTemplate = await vite.transformIndexHtml(req.originalUrl, indexHtml) // Load (to be bundled) entry point for server side rendering const { render } = await vite.ssrLoadModule('./client/entry-server.jsx') const html = transformedTemplate.replace('', render(req.originalUrl)) res.send(html) } catch (error) { vite.ssrFixStacktrace(error) next(error) } }) return r } async function createProductionRouter() { // Load bundled entry point for server side rendering const { render } = await import('./dist/server/entry-server.js') const r = new express.Router() r.use('/', express.static('dist/client')) r.use('*', async (req, res) => { const transformedTemplate = await fs.readFile( path.resolve('./dist/client/index.html'), 'utf-8' ) const html = transformedTemplate.replace('', render(req.originalUrl)) res.send(html) }) return r } async function main() { const app = express() app.use('/', await createApiRouter()) if (config.isDevelopment) { app.use('/', await createDevRouter()) } else { app.use('/', await createProductionRouter()) } app.listen(config.port, () => { console.log(`Listening on port ${config.port}...`) }) } main()