Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: dynamic import server routes #494

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
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
11 changes: 10 additions & 1 deletion packages/react-server/examples/minimal/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import Link from "next/link";
import type React from "react";

export default function Layout(props: React.PropsWithChildren) {
return (
<html>
<body>
<div>[Layout]</div>
<h3>[Layout]</h3>
<ul>
<li>
<Link href="/">Home</Link>
</li>
<li>
<Link href="/test">Test</Link>
</li>
</ul>
{props.children}
</body>
</html>
Expand Down
6 changes: 3 additions & 3 deletions packages/react-server/examples/minimal/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { TestClient } from "./_client";

export default function Page() {
return (
<>
<div>[Page]</div>
<div>
<h3>[Home]</h3>
<TestClient />
<form action={changeCount}>
<button>Action: {getCount()}</button>
</form>
</>
</div>
);
}
10 changes: 10 additions & 0 deletions packages/react-server/examples/minimal/app/test/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import "./test.css";

export default function Page() {
return (
<div>
<h3>Test</h3>
<div className="test-css">hello</div>
</div>
);
}
3 changes: 3 additions & 0 deletions packages/react-server/examples/minimal/app/test/test.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.test-css {
background-color: #dfd;
}
4 changes: 2 additions & 2 deletions packages/react-server/src/features/assets/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export function vitePluginServerAssets({
];
}

export function serverAssertsPluginServer({
export function serverAssetsPluginServer({
manager,
}: { manager: PluginStateManager }): Plugin[] {
// 0. track server assets during server build (this plugin)
Expand All @@ -160,7 +160,7 @@ export function serverAssertsPluginServer({

return [
{
name: serverAssertsPluginServer.name + ":build",
name: serverAssetsPluginServer.name + ":build",
apply: "build",
generateBundle(_options, bundle) {
if (manager.buildType !== "server") {
Expand Down
2 changes: 1 addition & 1 deletion packages/react-server/src/features/prerender/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ function createPrerenderPresets(manifest: RouteModuleManifest) {
generateStaticParams: async () => {
const result: string[] = [];
for (const entry of entries) {
const page = entry.module?.page;
const page = await entry.module?.page?.();
if (page && entry.dynamic && page.generateStaticParams) {
const generated = await page.generateStaticParams();
for (const params of generated) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,20 @@ exports[`generateRouteModuleTree > basic 1`] = `
"children": {
"y": {
"value": {
"layout": {
"default": "/X/Y/LAYOUT.TSX",
},
"page": {
"default": "/X/Y/PAGE.TSX",
},
"layout": [Function],
"page": [Function],
},
},
},
"value": {
"error": {
"default": "/X/ERROR.TSX",
},
"page": {
"default": "/X/PAGE.TSX",
},
"error": [Function],
"page": [Function],
},
},
},
"value": {
"layout": {
"default": "/LAYOUT.TSX",
},
"page": {
"default": "/PAGE.TSX",
},
"layout": [Function],
"page": [Function],
},
},
},
Expand Down Expand Up @@ -404,31 +392,7 @@ exports[`generateRouteModuleTree > basic 4`] = `
},
"metadata": <React.Fragment />,
"pages": {
"/z": <ThrowNotFound
params={{}}
request={
{
"headers": {},
"url": "https://test.local/z",
}
}
searchParams={{}}
url={
{
"hash": "",
"host": "test.local",
"hostname": "test.local",
"href": "https://test.local/z",
"origin": "https://test.local",
"password": "",
"pathname": "/z",
"port": "",
"protocol": "https:",
"search": "",
"username": "",
}
}
/>,
"/z": <ThrowNotFound />,
},
"params": [
[
Expand Down
7 changes: 5 additions & 2 deletions packages/react-server/src/features/router/api-route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { injectResponseCookies } from "../next/cookie";
import type { RequestContext } from "../request-context/server";
import type { RouteModuleTree } from "./server";
import { type RouteModuleTree } from "./server";
import { type MatchParams, matchRouteTree, toMatchParamsObject } from "./tree";

// https://nextjs.org/docs/app/api-reference/file-conventions/route
Expand Down Expand Up @@ -32,7 +32,10 @@ export async function handleApiRoutes(
const url = new URL(request.url);
const { matches } = matchRouteTree(tree, url.pathname);
for (const m of matches) {
const handler = m.type === "page" && m.node.value?.route?.[method];
if (m.type !== "page") continue;

const route = await m.node.value?.route?.();
const handler = route?.[method];
if (handler) {
const params = toMatchParamsObject(m.params);
const response = await requestContext.run(() =>
Expand Down
2 changes: 1 addition & 1 deletion packages/react-server/src/features/router/server.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ describe(generateRouteModuleTree, () => {
"/x/y/page.tsx",
];
const input = Object.fromEntries(
files.map((k) => [k, { default: k.toUpperCase() }]),
files.map((k) => [k, async () => ({ default: k.toUpperCase() })]),
);
const { tree } = generateRouteModuleTree(input);
expect(tree).toMatchSnapshot();
Expand Down
56 changes: 32 additions & 24 deletions packages/react-server/src/features/router/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,29 @@ import {

// cf. https://nextjs.org/docs/app/building-your-application/routing#file-conventions
export interface RouteModule {
page?: {
page?: () => Promise<{
default: React.FC<PageProps>;
metadata?: Metadata;
generateStaticParams?: () => Promise<Record<string, string>[]>;
};
layout?: {
}>;
layout?: () => Promise<{
default: React.FC<LayoutProps>;
metadata?: Metadata;
};
error?: {
}>;
error?: () => Promise<{
// TODO: warn if no "use client"
default: React.FC<ErrorPageProps>;
};
"not-found"?: {
}>;
"not-found"?: () => Promise<{
default: React.FC;
};
loading?: {
}>;
loading?: () => Promise<{
default: React.FC;
};
template?: {
}>;
template?: () => Promise<{
default: React.FC<{ children?: React.ReactNode }>;
};
route?: ApiRouteMoudle;
}>;
route?: () => Promise<ApiRouteMoudle>;
}

export type RouteModuleKey = keyof RouteModule;
Expand All @@ -55,9 +55,9 @@ function importRuntimeClient(): Promise<typeof import("../../runtime/client")> {
return import("@hiogawa/react-server/runtime/client" as string);
}

function renderPage(node: RouteModuleTree, props: PageProps) {
const Page = node.value?.page?.default ?? ThrowNotFound;
return <Page {...props} />;
async function renderPage(node: RouteModuleTree, props: PageProps) {
const Page = await node.value?.page?.().then((v) => v.default);
return Page ? <Page {...props} /> : <ThrowNotFound />;
}

async function renderLayout(
Expand All @@ -77,19 +77,21 @@ async function renderLayout(
let acc = <LayoutContent name={prefix} />;
acc = <RedirectBoundary>{acc}</RedirectBoundary>;

const NotFoundPage = node.value?.["not-found"]?.default;
const NotFoundPage = await node.value?.["not-found"]?.().then(
(v) => v.default,
);
if (NotFoundPage) {
acc = (
<NotFoundBoundary fallback={<NotFoundPage />}>{acc}</NotFoundBoundary>
);
}

const ErrorPage = node.value?.error?.default;
const ErrorPage = await node.value?.error?.().then((v) => v.default);
if (ErrorPage) {
acc = <ErrorBoundary errorComponent={ErrorPage}>{acc}</ErrorBoundary>;
}

const LoadingPage = node.value?.loading?.default;
const LoadingPage = await node.value?.loading?.().then((v) => v.default);
if (LoadingPage) {
acc = (
<RemountRoute>
Expand All @@ -98,7 +100,7 @@ async function renderLayout(
);
}

const TemplatePage = node.value?.template?.default;
const TemplatePage = await node.value?.template?.().then((v) => v.default);
if (TemplatePage) {
acc = (
<RemountRoute>
Expand All @@ -107,7 +109,7 @@ async function renderLayout(
);
}

const Layout = node.value?.layout?.default;
const Layout = await node.value?.layout?.().then((v) => v.default);
if (Layout) {
acc = (
<Layout key={prefix} {...props}>
Expand Down Expand Up @@ -146,10 +148,16 @@ export async function renderRouteMap(
};
if (m.type === "layout") {
layouts[m.prefix] = await renderLayout(m.node, props, m);
Object.assign(metadata, m.node.value?.layout?.metadata);
Object.assign(
metadata,
await m.node.value?.layout?.().then((v) => v.metadata),
);
} else if (m.type === "page") {
pages[m.prefix] = renderPage(m.node, props);
Object.assign(metadata, m.node.value?.page?.metadata);
pages[m.prefix] = await renderPage(m.node, props);
Object.assign(
metadata,
await m.node.value?.page?.().then((v) => v.metadata),
);
} else {
m.type satisfies never;
}
Expand Down
5 changes: 2 additions & 3 deletions packages/react-server/src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
} from "vite";
import { CSS_LANGS_RE } from "../features/assets/css";
import {
serverAssertsPluginServer,
serverAssetsPluginServer,
vitePluginServerAssets,
} from "../features/assets/plugin";
import { SERVER_CSS_PROXY } from "../features/assets/shared";
Expand Down Expand Up @@ -175,7 +175,6 @@ export function vitePluginReactServer(options?: {
return `
const glob = import.meta.glob(
"/${routeDir}/**/(page|layout|error|not-found|loading|template|route).(js|jsx|ts|tsx)",
{ eager: true },
);
export default Object.fromEntries(
Object.entries(glob).map(
Expand Down Expand Up @@ -211,7 +210,7 @@ export function vitePluginReactServer(options?: {
"server-only": true,
}),

serverAssertsPluginServer({ manager }),
serverAssetsPluginServer({ manager }),

{
name: "patch-react-server-dom-webpack",
Expand Down