Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .changeset/guarded-lazy-compilation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'rsbuild-plugin-react-router': minor
---

Expose a plugin-level `lazyCompilation` option that keeps React Router hydration
modules eager while preserving user lazy compilation filters.
14 changes: 14 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import {
import { warnOnClientSourceMaps } from './warnings/warn-on-client-source-maps.js';
import { validatePluginOrderFromConfig } from './validation/validate-plugin-order.js';
import { getSsrExternals } from './ssr-externals.js';
import { guardReactRouterLazyCompilation } from './lazy-compilation.js';

const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);

Expand Down Expand Up @@ -1082,6 +1083,18 @@ export const pluginReactRouter = (
/\.js$/,
''
);
const requestedLazyCompilation =
pluginOptions.lazyCompilation === undefined
? config.dev?.lazyCompilation
: pluginOptions.lazyCompilation;
const guardedLazyCompilation = guardReactRouterLazyCompilation({
lazyCompilation: requestedLazyCompilation,
entryClientPath: finalEntryClientPath,
});
const devLazyCompilation =
guardedLazyCompilation === undefined
? {}
: { lazyCompilation: guardedLazyCompilation };

const nodeEntries: Record<string, string> = {
...(hasServerApp
Expand Down Expand Up @@ -1110,6 +1123,7 @@ export const pluginReactRouter = (
},
dev: {
writeToDisk: true,
...devLazyCompilation,
// Only add SSR middleware if SSR is enabled and not using a custom server
// In SPA mode (ssr: false), we just serve static files from the client build
setupMiddlewares:
Expand Down
94 changes: 94 additions & 0 deletions src/lazy-compilation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { BUILD_CLIENT_ROUTE_QUERY_STRING } from './constants.js';
import type { PluginOptions } from './types.js';

type LazyCompilationOptions = Exclude<
NonNullable<PluginOptions['lazyCompilation']>,
boolean
>;

type LazyCompilationModule = {
request?: string;
userRequest?: string;
rawRequest?: string;
resource?: string;
identifier?: () => string;
nameForCondition?: () => string | null;
};

const normalizeSlashes = (value: string): string => value.replace(/\\/g, '/');

const getLazyCompilationModuleValues = (
module: LazyCompilationModule
): string[] =>
[
module.request,
module.userRequest,
module.rawRequest,
module.resource,
module.identifier?.(),
module.nameForCondition?.(),
].filter((value): value is string => Boolean(value));

const matchesLazyCompilationTest = (
test: LazyCompilationOptions['test'] | undefined,
module: LazyCompilationModule
): boolean => {
if (!test) {
return true;
}
if (typeof test === 'function') {
return test(module as Parameters<typeof test>[0]);
}
const conditionName = module.nameForCondition?.();
if (!conditionName) {
return false;
}
test.lastIndex = 0;
return test.test(conditionName);
};

const createReactRouterHydrationModuleTest = (entryClientPath: string) => {
const eagerPatterns = [
normalizeSlashes(entryClientPath),
'virtual/react-router/browser-manifest',
BUILD_CLIENT_ROUTE_QUERY_STRING,
'?react-router-route',
];

return (module: LazyCompilationModule): boolean =>
getLazyCompilationModuleValues(module).some(value => {
const normalizedValue = normalizeSlashes(value);
return eagerPatterns.some(pattern => normalizedValue.includes(pattern));
});
};

export const guardReactRouterLazyCompilation = ({
lazyCompilation,
entryClientPath,
}: {
lazyCompilation: PluginOptions['lazyCompilation'] | undefined;
entryClientPath: string;
}): PluginOptions['lazyCompilation'] | undefined => {
if (lazyCompilation === undefined || lazyCompilation === false) {
return lazyCompilation;
}

const options: LazyCompilationOptions =
lazyCompilation === true
? { entries: true, imports: true }
: lazyCompilation;
const userTest = options.test;
const isReactRouterHydrationModule =
createReactRouterHydrationModuleTest(entryClientPath);

return {
...options,
test(module) {
const lazyModule = module as LazyCompilationModule;
if (isReactRouterHydrationModule(lazyModule)) {
return false;
}
return matchesLazyCompilationTest(userTest, lazyModule);
},
};
};
12 changes: 12 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { RsbuildConfig } from '@rsbuild/core';

export type Route = {
id: string;
parentId?: string;
Expand Down Expand Up @@ -27,6 +29,16 @@ export type PluginOptions = {
* Federation mode configuration
*/
federation?: boolean;

/**
* Opt in to Rsbuild's dev-only lazy compilation behavior.
*
* React Router hydration modules remain eager so initial dev requests can
* load the browser manifest and route modules without lazy proxy delays.
*
* @default undefined
*/
lazyCompilation?: NonNullable<RsbuildConfig['dev']>['lazyCompilation'];
};

/**
Expand Down
126 changes: 126 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,28 @@ import { createStubRsbuild } from '@scripts/test-helper';
import { describe, expect, it } from '@rstest/core';
import { pluginReactRouter } from '../src';

type LazyCompilationTestModule = {
resource?: string;
nameForCondition?: () => string | null;
};

type LazyCompilationConfig = {
test?: (module: LazyCompilationTestModule) => boolean;
};

const getLazyCompilationTest = (
lazyCompilation: boolean | LazyCompilationConfig | undefined
) => {
if (
!lazyCompilation ||
typeof lazyCompilation === 'boolean' ||
typeof lazyCompilation.test !== 'function'
) {
throw new Error('Expected lazy compilation to install a test function.');
}
return lazyCompilation.test;
};

describe('pluginReactRouter', () => {
it('should configure basic plugin options', async () => {
const rsbuild = await createStubRsbuild({
Expand Down Expand Up @@ -31,6 +53,110 @@ describe('pluginReactRouter', () => {
expect(nodeConfig.output.module).toBe(false);
});

it('should forward lazy compilation when explicitly configured', async () => {
const rsbuild = await createStubRsbuild({
rsbuildConfig: {},
});

rsbuild.addPlugins([
pluginReactRouter({
lazyCompilation: {
entries: true,
imports: true,
},
}),
]);
const config = await rsbuild.unwrapConfig();

expect(config.dev.lazyCompilation).toMatchObject({
entries: true,
imports: true,
});
const test = getLazyCompilationTest(config.dev.lazyCompilation);
expect(
test({
resource: '/project/app/root.tsx?__react-router-build-client-route',
})
).toBe(false);
expect(
test({
resource: '/project/app/components/card.tsx',
nameForCondition: () => '/project/app/components/card.tsx',
})
).toBe(true);
});

it('should allow lazy compilation to be enabled with a boolean', async () => {
const rsbuild = await createStubRsbuild({
rsbuildConfig: {},
});

rsbuild.addPlugins([pluginReactRouter({ lazyCompilation: true })]);
const config = await rsbuild.unwrapConfig();

expect(config.dev.lazyCompilation).toMatchObject({
entries: true,
imports: true,
});
const test = getLazyCompilationTest(config.dev.lazyCompilation);
expect(
test({
resource: `${process.cwd()}/app/entry.client.tsx`,
})
).toBe(false);
});

it('guards direct Rsbuild lazy compilation config for React Router hydration entries', async () => {
const rsbuild = await createStubRsbuild({
rsbuildConfig: {
dev: {
lazyCompilation: {
entries: true,
imports: false,
test: /app/,
},
},
},
});

rsbuild.addPlugins([pluginReactRouter()]);
const config = await rsbuild.unwrapConfig();

expect(config.dev.lazyCompilation).toMatchObject({
entries: true,
imports: false,
});
const test = getLazyCompilationTest(config.dev.lazyCompilation);
expect(
test({
resource: '/project/app/routes/home.tsx?__react-router-build-client-route',
})
).toBe(false);
expect(
test({
resource: '/project/app/components/card.tsx',
nameForCondition: () => '/project/app/components/card.tsx',
})
).toBe(true);
expect(
test({
resource: '/project/vendor/react.tsx',
nameForCondition: () => '/project/vendor/react.tsx',
})
).toBe(false);
});

it('should allow lazy compilation to be disabled', async () => {
const rsbuild = await createStubRsbuild({
rsbuildConfig: {},
});

rsbuild.addPlugins([pluginReactRouter({ lazyCompilation: false })]);
const config = await rsbuild.unwrapConfig();

expect(config.dev.lazyCompilation).toBe(false);
});

it('should configure web environment correctly', async () => {
const rsbuild = await createStubRsbuild({
rsbuildConfig: {},
Expand Down
Loading
Loading