| 19 | const __dirname = path.dirname(__filename) |
| 20 | |
| 21 | export const createServer = async ( |
| 22 | root = process.cwd(), |
| 23 | isProd = process.env.NODE_ENV === 'production', |
| 24 | ) => { |
| 25 | const app = express() |
| 26 | |
| 27 | app.use('/trpc', trpcMiddleWare as any) |
| 28 | |
| 29 | if (!isProd) { |
| 30 | const vite = await import('vite') |
| 31 | const viteServer = await vite.createServer({ |
| 32 | root, |
| 33 | logLevel: isTest ? 'error' : 'info', |
| 34 | server: { |
| 35 | middlewareMode: true, |
| 36 | watch: { |
| 37 | // During tests we edit the files too fast and sometimes chokidar |
| 38 | // misses change events, so enforce polling for consistency |
| 39 | usePolling: true, |
| 40 | interval: 100, |
| 41 | }, |
| 42 | hmr: { |
| 43 | port: HMR_PORT, |
| 44 | }, |
| 45 | }, |
| 46 | appType: 'custom', |
| 47 | }) |
| 48 | |
| 49 | // Use vite's connect instance as middleware |
| 50 | app.use(viteServer.middlewares) |
| 51 | |
| 52 | // Handle any requests that don't match an API route by serving the React app's index.html |
| 53 | app.get('/{*splat}', async (req, res, next) => { |
| 54 | try { |
| 55 | let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8') |
| 56 | |
| 57 | // Transform HTML using Vite plugins. |
| 58 | html = await viteServer.transformIndexHtml(req.url, html) |
| 59 | |
| 60 | res.send(html) |
| 61 | } catch (e) { |
| 62 | return next(e) |
| 63 | } |
| 64 | }) |
| 65 | |
| 66 | return { app } |
| 67 | } else { |
| 68 | app.use(express.static(path.resolve(__dirname, '../client'))) |
| 69 | |
| 70 | // Handle any requests that don't match an API route by serving the React app's index.html |
| 71 | app.get('/{*splat}', (req, res) => { |
| 72 | res.sendFile(path.resolve(__dirname, '../client', 'index.html')) |
| 73 | }) |
| 74 | } |
| 75 | |
| 76 | return { app } |
| 77 | } |
| 78 | |