Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/spa-build-process.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'rsbuild-plugin-react-router': patch
---

Fix two `ssr: false` / prerender build issues:

- `rsbuild build` no longer hangs when the app's server graph opens a ref'd handle at module scope (for example a `BroadcastChannel`). Build-time rendering (SPA-mode `index.html` and prerendering, classic and RSC) now evaluates the server bundle in a worker thread that is terminated once rendering is done, instead of importing it into the build process (#135).
- With `performance.buildCache` enabled, a warm build no longer renders `index.html` against the previous build's asset URLs. The server-manifest module now declares a file dependency on the captured manifest, so Rspack's persistent cache invalidates it whenever the web build's asset names change (#136).
7 changes: 4 additions & 3 deletions .github/workflows/e2e-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ jobs:
- name: Install dependencies
run: pnpm install

- name: Run unit tests
run: pnpm test

# Unit tests exercise the built server-build worker (dist/).
- name: Build package
run: pnpm build

- name: Run unit tests
run: pnpm test

- name: Run publint
run: npx publint --errors-only

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ React Router's SPA Mode still requires a build-time server render of the root ro
When `ssr: false`:

- The plugin builds both `web` and `node` internally.
- It generates `build/client/index.html` by running the server build once (requesting `basename` with the `X-React-Router-SPA-Mode: yes` header).
- It generates `build/client/index.html` by running the server build once (requesting `basename` with the `X-React-Router-SPA-Mode: yes` header). The server bundle is evaluated in a worker thread that is terminated afterwards, with `process.env.IS_RR_BUILD_REQUEST === 'yes'` set, so module-scope side effects in your root route's import graph run at build time but cannot keep `rsbuild build` alive. The same applies to prerendering.
- It removes `build/server` after generating `index.html`, so the output is deployable as static assets.

**Important:** In SPA mode, use `clientLoader` instead of `loader` for data loading since there's no server at runtime.
Expand Down
1 change: 1 addition & 0 deletions rslib.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const config = defineConfig({
'route-module-transform-loader':
'./src/route-module-transform-loader.ts',
'rsc-route-transform-loader': './src/rsc-route-transform-loader.ts',
'server-build-worker': './src/server-build-worker.ts',
'templates/entry.server': './src/templates/entry.server.tsx',
'templates/entry.client': './src/templates/entry.client.tsx',
'templates/entry.rsc': './src/templates/entry.rsc.tsx',
Expand Down
11 changes: 11 additions & 0 deletions src/build-output-transforms.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { existsSync } from 'node:fs';
import type { RsbuildPluginAPI, TransformHandler } from '@rsbuild/core';
import jsesc from 'jsesc';
import { relative } from 'pathe';
Expand Down Expand Up @@ -80,6 +81,8 @@ type RegisterBuildOutputTransformsOptions = {
resolvedServerOutput: 'module' | 'commonjs';
performanceProfiler: ReactRouterPerformanceProfiler;
getLatestServerManifest: () => ReactRouterManifest | null;
/** File holding the captured manifests; a dependency of the server-manifest module. */
serverManifestStampPath: string;
getLatestServerManifestByBundleId: (
bundleId: string
) => ReactRouterManifest | undefined;
Expand Down Expand Up @@ -112,6 +115,7 @@ export const registerBuildOutputTransforms = ({
resolvedServerOutput,
performanceProfiler,
getLatestServerManifest,
serverManifestStampPath,
getLatestServerManifestByBundleId,
routes,
pluginOptions,
Expand Down Expand Up @@ -205,6 +209,13 @@ export const registerBuildOutputTransforms = ({
};
}

// Cache identity for a module whose source never changes (#136);
// see `serverManifestStampPath` in index.ts.
if (existsSync(serverManifestStampPath)) {
args.addDependency(serverManifestStampPath);
} else {
args.addMissingDependency(serverManifestStampPath);
}
const bundleMatch = args.resource.match(
/virtual\/react-router\/server-manifest(?:-([^?]+))?/
);
Expand Down
26 changes: 26 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,30 @@ export const pluginReactRouter = (
let latestServerManifest: ReactRouterManifest | null = null;
const latestServerManifestsByBundleId: Record<string, ReactRouterManifest> =
{};
// The node `server-manifest` module's source is a constant; its real
// content is injected by a transform from the web compilation's emitted
// asset names. Rspack's persistent cache would therefore reuse a previous
// build's module even when those names changed (#136). The transform
// declares this file, which holds the captured manifests, as a file
// dependency so the cache invalidates exactly when the manifest changes.
const serverManifestStampPath = resolve(
api.context.cachePath,
'react-router',
'server-manifest.json'
);
// Bundle manifests derive from the base one, so the base is the stamp.
// Only rewrite on change: a bumped mtime would otherwise invalidate the
// module on every build and, if the cache dir is watched, rebuild node
// after every web rebuild in dev.
const writeServerManifestStamp = (): void => {
const stamp = JSON.stringify(latestServerManifest);
const previous = existsSync(serverManifestStampPath)
? readFileSync(serverManifestStampPath, 'utf8')
: undefined;
if (stamp !== previous) {
fsExtra.outputFileSync(serverManifestStampPath, stamp);
}
};

const routeByFilePath = new Map(
Object.values(routes).map(route => [
Expand Down Expand Up @@ -756,6 +780,7 @@ export const pluginReactRouter = (
latestServerManifestsByBundleId[bundleId] = bundleManifest;
manifestsByEntryName[entryName] = bundleManifest;
}
writeServerManifestStamp();

if (!isBuild) {
modePlan.artifacts.devRuntime.captureWeb(
Expand Down Expand Up @@ -1159,6 +1184,7 @@ export const pluginReactRouter = (
resolvedServerOutput,
performanceProfiler,
getLatestServerManifest: () => latestServerManifest,
serverManifestStampPath,
getLatestServerManifestByBundleId: bundleId =>
latestServerManifestsByBundleId[bundleId],
routes,
Expand Down
162 changes: 76 additions & 86 deletions src/prerender-build.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { existsSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
import fsExtra from 'fs-extra';
import * as Effect from 'effect/Effect';
import type { RsbuildPluginAPI } from '@rsbuild/core';
import {
createRequestHandler,
matchRoutes,
type ServerBuild,
} from 'react-router';
import { matchRoutes } from 'react-router';
import { dirname, relative, resolve } from 'pathe';
import { PLUGIN_NAME, SPA_FALLBACK_HTML_FILE } from './constants.js';
import { getBuildManifest } from './build-manifest.js';
Expand All @@ -31,24 +26,11 @@ import type {
Config,
ResolvedReactRouterConfig,
} from './react-router-config.js';
import { resolveServerBuildModule } from './server-utils.js';
import { startServerBuildWorker } from './server-build-worker-client.js';
import type { ServerBuildDescription } from './server-build-worker-protocol.js';
import type { PluginOptions, Route } from './types.js';
import { runPluginEffect, tryPluginPromise } from './effect-runtime.js';

type BuildRouteModule = {
loader?: unknown;
default?: unknown;
ErrorBoundary?: unknown;
};

type PrerenderServerBuild = ServerBuild & {
routes: Record<string, { id?: string; module?: BuildRouteModule }>;
assets?: {
routes?: Record<string, { hasLoader?: boolean }>;
};
prerender?: string[];
};

type PrerenderBuildApi = Pick<
RsbuildPluginAPI,
'logger' | 'getNormalizedConfig'
Expand Down Expand Up @@ -344,7 +326,7 @@ const handleSpaMode = async ({
api,
}: {
handler: (request: Request) => Promise<Response>;
build: PrerenderServerBuild;
build: ServerBuildDescription;
clientBuildDir: string;
basename: string;
api: PrerenderBuildApi;
Expand Down Expand Up @@ -459,7 +441,7 @@ const createPrerenderPathEffect = ({
options,
}: {
path: string;
build: PrerenderServerBuild;
build: ServerBuildDescription;
buildRoutes: ReturnType<typeof createPrerenderRoutes>;
requestHandler: (request: Request) => Promise<Response>;
clientBuildDir: string;
Expand Down Expand Up @@ -596,75 +578,83 @@ export const runReactRouterPrerenderBuild = async (
await mkdir(clientBuildDir, { recursive: true });

if (!ssr || isPrerenderEnabled) {
process.env.IS_RR_BUILD_REQUEST = 'yes';
const buildModule = await import(pathToFileURL(serverBuildPath).toString());
const build = (await resolveServerBuildModule(
buildModule,
`Server build ${JSON.stringify(serverBuildPath)}`
)) as PrerenderServerBuild;
const requestHandler = createRequestHandler(build, 'production');

if (isPrerenderEnabled) {
if (!ssr) {
const generated = latestBrowserManifest
? {
manifest: latestBrowserManifest,
moduleExportsByRouteId: latestBrowserManifestModuleExports,
}
: await generateReactRouterManifestForDev(
routes,
pluginOptions,
clientStats,
appDirectory,
assetPrefix,
createReactRouterManifestOptions({
routeChunks: routeChunkOptions,
routeModuleAnalysis,
})
);
assertValidSsrFalsePrerenderExports({
routes,
manifestRoutes: generated.manifest.routes,
routeExports: generated.moduleExportsByRouteId,
prerenderPaths,
api,
});
const worker = await startServerBuildWorker({
serverBuildPath,
mode: 'classic',
});
try {
const build = worker.description;
if (!build) {
throw new Error(
`[${PLUGIN_NAME}] Server build worker returned no build description`
);
}
const requestHandler = worker.handler;

if (isPrerenderEnabled) {
if (!ssr) {
const generated = latestBrowserManifest
? {
manifest: latestBrowserManifest,
moduleExportsByRouteId: latestBrowserManifestModuleExports,
}
: await generateReactRouterManifestForDev(
routes,
pluginOptions,
clientStats,
appDirectory,
assetPrefix,
createReactRouterManifestOptions({
routeChunks: routeChunkOptions,
routeModuleAnalysis,
})
);
assertValidSsrFalsePrerenderExports({
routes,
manifestRoutes: generated.manifest.routes,
routeExports: generated.moduleExportsByRouteId,
prerenderPaths,
api,
});
}

validatePrerenderPathMatches(routes, prerenderPaths);

validatePrerenderPathMatches(routes, prerenderPaths);
if (prerenderPaths.length > 0) {
api.logger.info(
`Prerender (html): ${prerenderPaths.length} path(s)...`
);
}

if (prerenderPaths.length > 0) {
api.logger.info(
`Prerender (html): ${prerenderPaths.length} path(s)...`
const buildRoutes = createPrerenderRoutes(build.routes);
await runPluginEffect(
createBoundedPrerenderTasksEffect(
prerenderPaths,
getPrerenderConcurrency(prerenderConfig),
path =>
createPrerenderPathEffect({
path,
build,
buildRoutes,
requestHandler,
clientBuildDir,
options,
})
)
);
}

const buildRoutes = createPrerenderRoutes(build.routes);
await runPluginEffect(
createBoundedPrerenderTasksEffect(
prerenderPaths,
getPrerenderConcurrency(prerenderConfig),
path =>
createPrerenderPathEffect({
path,
build,
buildRoutes,
requestHandler,
clientBuildDir,
options,
})
)
);
}

if (!ssr) {
await handleSpaMode({
handler: requestHandler,
build,
clientBuildDir,
basename,
api,
});
if (!ssr) {
await handleSpaMode({
handler: requestHandler,
build,
clientBuildDir,
basename,
api,
});
}
} finally {
await worker.close();
}
}

Expand Down
Loading
Loading