From eb7ba6a9b1643317e45b66a521a2dc0d72cd3976 Mon Sep 17 00:00:00 2001 From: xHomu <84349818+xHomu@users.noreply.github.com> Date: Sat, 16 Sep 2023 10:13:54 -0700 Subject: [PATCH] Update server.ts to v2 best practices https://github.com/remix-run/remix/issues/6919 Update chokidar to resolve a rare race condition issue that resultant in dev server crashing. This PR https://github.com/remix-run/remix/pull/7299 sets up a fix where we can watch the version.txt file for changes (rather than build/index.js directly) to avoid race condition. --- server/index.ts | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/server/index.ts b/server/index.ts index c3382ec5..a51a8181 100644 --- a/server/index.ts +++ b/server/index.ts @@ -13,7 +13,6 @@ import { import { wrapExpressCreateRequestHandler } from '@sentry/remix' import address from 'address' import chalk from 'chalk' -import chokidar from 'chokidar' import closeWithGrace from 'close-with-grace' import compression from 'compression' import express from 'express' @@ -22,10 +21,6 @@ import getPort, { portNumbers } from 'get-port' import helmet from 'helmet' import morgan from 'morgan' -// @ts-ignore - this file may not exist if you haven't built yet, but it will -// definitely exist by the time the dev or prod server actually runs. -import * as remixBuild from '#build/index.js' - installGlobals() const MODE = process.env.NODE_ENV @@ -35,8 +30,13 @@ const createRequestHandler = wrapExpressCreateRequestHandler( ) const BUILD_PATH = '../build/index.js' +const WATCH_PATH = '../build/version.txt' -const build = remixBuild as unknown as ServerBuild +/** + * Initial build + * @type {ServerBuild} + */ +const build = await import(BUILD_PATH) let devBuild = build const app = express() @@ -262,8 +262,14 @@ if (MODE === 'development') { broadcastDevReady(devBuild) } + // We'll import chokidar here so doesn't get bundled in production. + const chokidar = await import('chokidar') + const dirname = path.dirname(fileURLToPath(import.meta.url)) - const watchPath = path.join(dirname, BUILD_PATH).replace(/\\/g, '/') - const watcher = chokidar.watch(watchPath, { ignoreInitial: true }) - watcher.on('all', reloadBuild) + const watchPath = path.join(dirname, WATCH_PATH).replace(/\\/g, '/') + + chokidar + .watch(watchPath, { ignoreInitial: true }) + .on('add', reloadBuild) + .on('change', reloadBuild) }