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(react-server): dynamic import glob routes #278

Closed
wants to merge 3 commits into from
Closed
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
3 changes: 0 additions & 3 deletions packages/react-server/src/entry/react-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,6 @@ function createRouter() {
// for now hard code /src/routes as convention
const glob = import.meta.glob(
"/src/routes/**/(page|layout|error).(js|jsx|ts|tsx)",
{
eager: true,
},
);
const tree = generateRouteModuleTree(
objectMapKeys(glob, (_v, k) => k.slice("/src/routes".length)),
Expand Down
5 changes: 3 additions & 2 deletions packages/react-server/src/entry/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createMemoryHistory } from "@tanstack/history";
import ReactDOMServer from "react-dom/server.edge";
import type { ModuleNode, ViteDevServer } from "vite";
import type { SsrAssetsType } from "../features/assets/plugin";
import { DEV_SSR_CSS, SERVER_CSS_PROXY } from "../features/assets/shared";
import {
LayoutRoot,
LayoutStateContext,
Expand Down Expand Up @@ -135,8 +136,8 @@ export async function renderHtml(

if (import.meta.env.DEV) {
// ensure latest css
invalidateModule($__global.dev.server, "\0virtual:react-server-css.js");
invalidateModule($__global.dev.server, "\0virtual:dev-ssr-css.css?direct");
invalidateModule($__global.dev.server, `\0${SERVER_CSS_PROXY}`);
invalidateModule($__global.dev.server, `\0${DEV_SSR_CSS}?direct`);
}
const assets: SsrAssetsType = (await import("virtual:ssr-assets" as string))
.default;
Expand Down
9 changes: 4 additions & 5 deletions packages/react-server/src/features/assets/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ import {
createVirtualPlugin,
} from "../../plugin/utils";
import { collectStyle, collectStyleUrls } from "./css";
import { DEV_SSR_CSS, SERVER_CSS_PROXY } from "./shared";

export interface SsrAssetsType {
bootstrapModules: string[];
head: string;
}

export const SERVER_CSS_PROXY = "virtual:server-css-proxy.js";

export function vitePluginServerAssets({
manager,
}: { manager: PluginStateManager }): Plugin[] {
Expand All @@ -41,7 +40,7 @@ export function vitePluginServerAssets({
<link
data-ssr-dev-css
rel="stylesheet"
href="/@id/__x00__virtual:dev-ssr-css.css?direct"
href="/@id/__x00__${DEV_SSR_CSS}?direct"
/>
<script type="module">
import { createHotContext } from "/@vite/client";
Expand Down Expand Up @@ -90,7 +89,7 @@ export function vitePluginServerAssets({
tinyassert(false);
}),

createVirtualPlugin("dev-ssr-css.css", async () => {
createVirtualPlugin(DEV_SSR_CSS.split(":")[1]!, async () => {
tinyassert(!manager.buildType);
const styles = await Promise.all([
`/******* react-server ********/`,
Expand All @@ -105,7 +104,7 @@ export function vitePluginServerAssets({
return styles.join("\n\n");
}),

createVirtualPlugin(SERVER_CSS_PROXY.slice("virtual:".length), async () => {
createVirtualPlugin(SERVER_CSS_PROXY.split(":")[1]!, async () => {
// virtual module to proxy css imports from react server to client
// TODO: invalidate + full reload when add/remove css file?
if (!manager.buildType) {
Expand Down
2 changes: 2 additions & 0 deletions packages/react-server/src/features/assets/shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const SERVER_CSS_PROXY = "virtual:server-css-proxy.js";
export const DEV_SSR_CSS = "virtual:dev-ssr-css.css";
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
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
34 changes: 23 additions & 11 deletions packages/react-server/src/features/router/server.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { objectHas, tinyassert } from "@hiogawa/utils";
import React from "react";
import { type ReactServerErrorContext, createError } from "../../lib/error";
import { type TreeNode, createFsRouteTree, matchRouteTree } from "./tree";

// cf. https://nextjs.org/docs/app/building-your-application/routing#file-conventions
interface RouteEntry {
page?: {
page?: () => Promise<{
default: React.FC<PageProps>;
};
layout?: {
}>;
layout?: () => Promise<{
default: React.FC<LayoutProps>;
};
error?: {
}>;
error?: () => Promise<{
// TODO: warn if no "use client"
default: React.FC<ErrorPageProps>;
};
}>;
}

type RouteModuleNode = TreeNode<RouteEntry>;
Expand All @@ -27,8 +28,8 @@ function importRuntimeClient(): Promise<typeof import("../../runtime-client")> {
return import("@hiogawa/react-server/runtime-client" as string);
}

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

Expand All @@ -43,11 +44,11 @@ async function renderLayout(
let acc = <LayoutContent name={prefix} />;
acc = <RedirectBoundary>{acc}</RedirectBoundary>;

const ErrorPage = node.value?.error?.default;
const ErrorPage = await importDefault(node.value?.error);
if (ErrorPage) {
acc = <ErrorBoundary errorComponent={ErrorPage}>{acc}</ErrorBoundary>;
}
const Layout = node.value?.layout?.default;
const Layout = await importDefault(node.value?.layout);
if (Layout) {
acc = (
<Layout key={prefix} {...props}>
Expand Down Expand Up @@ -80,7 +81,7 @@ export async function renderRouteMap(
if (m.type === "layout") {
layouts[m.prefix] = await renderLayout(m.node, props, m.prefix);
} else if (m.type === "page") {
pages[m.prefix] = renderPage(m.node, props);
pages[m.prefix] = await renderPage(m.node, props);
} else {
m.type satisfies never;
}
Expand Down Expand Up @@ -131,3 +132,14 @@ export interface ErrorPageProps {
serverError?: ReactServerErrorContext;
reset: () => void;
}

async function importDefault<T>(
lazyMod?: () => Promise<{ default: T }>,
): Promise<T | undefined> {
if (lazyMod) {
const mod = await lazyMod();
tinyassert(objectHas(mod, "default"), `no deafult export found`);
return mod.default;
}
return;
}
6 changes: 2 additions & 4 deletions packages/react-server/src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,8 @@ import {
createServer,
} from "vite";
import { CSS_LANGS_RE } from "../features/assets/css";
import {
SERVER_CSS_PROXY,
vitePluginServerAssets,
} from "../features/assets/plugin";
import { vitePluginServerAssets } from "../features/assets/plugin";
import { SERVER_CSS_PROXY } from "../features/assets/shared";
import { prerenderPlugin } from "../features/prerender/plugin";
import type { RouteManifest } from "../features/router/manifest";
import {
Expand Down