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
23 changes: 23 additions & 0 deletions src/dev-server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { RsbuildConfig } from '@rsbuild/core';
import type { ServerBuild } from 'react-router';

export type ServerSetup = Exclude<
NonNullable<NonNullable<RsbuildConfig['server']>['setup']>,
unknown[]
>;

export type DevServerMiddleware = (
req: IncomingMessage,
res: ServerResponse,
Expand Down Expand Up @@ -63,3 +69,20 @@ export const createDevServerMiddleware = (
}
};
};

export const createReactRouterDevServerSetup = ({
loadBuild,
}: {
loadBuild: BuildProvider;
}): ServerSetup =>
function reactRouterDevServerSetup(context) {
if (context.action !== 'dev') {
return;
}
// The returned callback runs after Rsbuild registers its built-in
// middlewares, so static assets are served before the React Router
// request handler.
return () => {
context.server.middlewares.use(createDevServerMiddleware({ loadBuild }));
};
};
26 changes: 13 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
PLUGIN_NAME,
} from './constants.js';
import { guardReactRouterLazyCompilation } from './lazy-compilation.js';
import { createDevServerMiddleware } from './dev-server.js';
import { createReactRouterDevServerSetup } from './dev-server.js';
import {
generateWithProps,
findEntryFile,
Expand Down Expand Up @@ -768,19 +768,19 @@ export const pluginReactRouter = (
writeToDisk: true,
...lazyCompilation,
watchFiles: mergeWatchFiles(config.dev?.watchFiles, routeWatchFiles),
setupMiddlewares:
pluginOptions.customServer || !ssr
? []
: [
middlewares => {
middlewares.push(
createDevServerMiddleware({
loadBuild: devRuntime.createBuildLoader(),
})
);
},
],
},
...(pluginOptions.customServer || !ssr
? {}
: {
server: {
setup: [
createReactRouterDevServerSetup({
// Lazy: the dev runtime binding does not exist yet here.
loadBuild: () => devRuntime.createBuildLoader()(),
}),
],
},
}),
tools: {
rspack: {
plugins: [vmodPlugin],
Expand Down
49 changes: 48 additions & 1 deletion tests/features.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ import path from 'node:path';
import { pluginReactRouter } from '../src';
import { getVirtualModuleFilePath } from '../src/virtual-modules';

type ReactRouterTestGlobal = typeof globalThis & {
__reactRouterTestConfig?: unknown;
};

const testGlobal = globalThis as ReactRouterTestGlobal;

const getServerSetupNames = (config: {
server?: { setup?: unknown };
}): string[] =>
[config.server?.setup]
.flat()
.filter((fn): fn is (...args: unknown[]) => unknown => Boolean(fn))
.map(fn => fn.name);

describe('pluginReactRouter', () => {
describe('basic configuration', () => {
it('should apply default options when no options provided', async () => {
Expand All @@ -22,6 +36,21 @@ describe('pluginReactRouter', () => {
expect(config.dev.writeToDisk).toBe(true);
});

it('should register the dev server middleware via server.setup', async () => {
const rsbuild = await createStubRsbuild({
rsbuildConfig: {},
});

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

// The deprecated `dev.setupMiddlewares` API must stay untouched.
expect(config.dev.setupMiddlewares).toBeUndefined();
expect(getServerSetupNames(config)).toContain(
'reactRouterDevServerSetup'
);
});

it('should respect customServer option', async () => {
const rsbuild = await createStubRsbuild({
rsbuildConfig: {},
Expand All @@ -30,7 +59,25 @@ describe('pluginReactRouter', () => {
rsbuild.addPlugins([pluginReactRouter({ customServer: true })]);
const config = await rsbuild.unwrapConfig();

expect(config.dev.setupMiddlewares).toEqual([]);
expect(config.dev.setupMiddlewares).toBeUndefined();
expect(getServerSetupNames(config)).not.toContain(
'reactRouterDevServerSetup'
);
});

it('should not register the dev server middleware in SPA mode', async () => {
testGlobal.__reactRouterTestConfig = { ssr: false };
const rsbuild = await createStubRsbuild({
rsbuildConfig: {},
});

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

expect(config.dev.setupMiddlewares).toBeUndefined();
expect(getServerSetupNames(config)).not.toContain(
'reactRouterDevServerSetup'
);
});

it('should configure server output format correctly', async () => {
Expand Down
1 change: 0 additions & 1 deletion tests/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ rstest.mock('@scripts/test-helper', () => ({
hmr: true,
liveReload: true,
writeToDisk: false,
setupMiddlewares: [],
},
environments: {
web: {
Expand Down
Loading