From a68c8c41203eb39b94f15ae5ea34436f68ac0d4d Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Fri, 24 Jan 2025 09:41:13 +0100 Subject: [PATCH] Ensure server entry point can import serverContainer from server bundle in prod --- app/tailwind.scss | 2 +- package.json | 2 +- scripts/expose-server-container.js | 15 +++++++++++++++ server.ts | 4 +++- 4 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 scripts/expose-server-container.js diff --git a/app/tailwind.scss b/app/tailwind.scss index 39ef6df..cbf6b28 100644 --- a/app/tailwind.scss +++ b/app/tailwind.scss @@ -30,7 +30,7 @@ } hr { - @apply my-3 + @apply tw-my-3 } } diff --git a/package.json b/package.json index 241188e..41e289b 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "license": "MIT", "type": "module", "scripts": { - "build": "react-router build && tsc --project tsconfig.build-server.json", + "build": "react-router build && node scripts/expose-server-container.js && tsc --project tsconfig.build-server.json", "test": "vitest run", "test:ci": "npm run test -- --coverage", "lint": "npm run lint:js", diff --git a/scripts/expose-server-container.js b/scripts/expose-server-container.js new file mode 100644 index 0000000..3fb1e3d --- /dev/null +++ b/scripts/expose-server-container.js @@ -0,0 +1,15 @@ +/** + * Update generated server bundle so that it exports the serverContainer, in order to use it by the server.js script + */ +import { readFileSync, writeFileSync } from 'node:fs'; + +const serverBundle = 'build/server/index.js'; +const [lastLine, prevToLastLine, ...allLines] = readFileSync(serverBundle).toString().split('\n').reverse(); + +// Last two lines are the closing curly braces, and an empty line. We need to insert the export of the serverContainer +// right before the curly brace + +writeFileSync( + serverBundle, + Buffer.from([...allLines.reverse(), ' ,serverContainer,', prevToLastLine, lastLine].join('\n')), +); diff --git a/server.ts b/server.ts index d5e8760..106d407 100644 --- a/server.ts +++ b/server.ts @@ -1,6 +1,5 @@ import { createRequestHandler } from '@react-router/express'; import express from 'express'; -import { serverContainer } from './app/container/container.server'; const { NODE_ENV, SHLINK_DASHBOARD_PORT = '3005' } = process.env; const isProd = NODE_ENV === 'production'; @@ -27,6 +26,9 @@ const build = viteDevServer : await import('./server/index.js'); // Fork entity manager on every request +const { serverContainer } = isProd + ? build + : await import('./app/container/container.server'); app.use(serverContainer.emForkMiddleware); app.all('*', createRequestHandler({ build }));