feat: Improve building, make Vite files served statically in prod

This commit is contained in:
Jesse Wierzbinski 2023-12-08 15:51:48 -10:00
parent 241be497bd
commit 4924fa6d85
No known key found for this signature in database
3 changed files with 37 additions and 12 deletions

View file

@ -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,
});

View file

@ -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,8 +128,14 @@ 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,
@ -137,6 +147,7 @@ Bun.serve({
return proxy;
}
}
}
if (new URL(req.url).pathname.startsWith("/assets")) {
// Serve from pages/dist/assets

View file

@ -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",