diff --git a/build.ts b/build.ts index 6467a466..bea87085 100644 --- a/build.ts +++ b/build.ts @@ -1,5 +1,10 @@ // Delete dist directory -import { rm } from "fs/promises"; +import { rm, cp, mkdir, exists } from "fs/promises"; + +if (!(await exists("./pages/dist"))) { + console.log("Please build the Vite server first, or use `bun prod-build`"); + process.exit(1); +} await rm("./dist", { recursive: true }); @@ -11,3 +16,11 @@ await Bun.build({ minify: true, external: ["bullmq", "@prisma/client"], }); + +// Create pages directory +await mkdir("./dist/pages"); + +// Copy Vite build output to dist +await cp("./pages/dist", "./dist/pages/", { + recursive: true, +}); diff --git a/index.ts b/index.ts index c0ee5c56..1b0a7c5c 100644 --- a/index.ts +++ b/index.ts @@ -23,6 +23,10 @@ server.emit(HookTypes.PreServe); const config = getConfig(); const requests_log = Bun.file(process.cwd() + "/logs/requests.log"); +// NODE_ENV seems to be broken and output `development` even when set to production, so use the flag instead +const isProd = + process.env.NODE_ENV === "production" || process.argv.includes("--prod"); + if (!(await requests_log.exists())) { console.log(`${chalk.green(`✓`)} ${chalk.bold("Creating logs folder...")}`); await mkdir(process.cwd() + "/logs"); @@ -124,17 +128,24 @@ Bun.serve({ if ( routes.find(route => route.path === new URL(req.url).pathname) ) { - // Proxy response from Vite at localhost:5173 + // Proxy response from Vite at localhost:5173 if in development mode + if (isProd) { + // Serve from pages/dist + return new Response( + // @ts-expect-error Custom Bun extension + Bun.file(`./pages/dist/index.html`) + ); + } else { + const proxy = await fetch( + req.url.replace( + config.http.base_url, + "http://localhost:5173" + ) + ); - const proxy = await fetch( - req.url.replace( - config.http.base_url, - "http://localhost:5173" - ) - ); - - if (proxy.status !== 404) { - return proxy; + if (proxy.status !== 404) { + return proxy; + } } } diff --git a/package.json b/package.json index 51722cb4..93a29123 100644 --- a/package.json +++ b/package.json @@ -35,10 +35,11 @@ "dev": "bun run index.ts", "vite:dev": "bunx --bun vite pages", "vite:build": "bunx --bun vite build pages", - "start": "NODE_ENV=production bun run index.ts & bunx --bun vite preview pages --port 5173", + "start": "NODE_ENV=production bun run dist/index.js --prod", "migrate-dev": "bun prisma migrate dev", "migrate": "bun prisma migrate deploy", "lint": "eslint --config .eslintrc.cjs --ext .ts .", + "prod-build": "bunx --bun vite build pages && bun run build.ts", "prisma": "DATABASE_URL=$(bun run prisma.ts) bunx prisma", "generate": "bun prisma generate", "benchmark:timeline": "bun run benchmarks/timelines.ts",