diff --git a/packages/vinext/src/entries/app-rsc-entry.ts b/packages/vinext/src/entries/app-rsc-entry.ts index bfcabea919..eaeb18a836 100644 --- a/packages/vinext/src/entries/app-rsc-entry.ts +++ b/packages/vinext/src/entries/app-rsc-entry.ts @@ -330,7 +330,13 @@ ${ } from ${JSON.stringify(appRouteHandlerResponsePath)};` : "" } -const __loadAppRouteHandlerDispatch = () => import(${JSON.stringify(appRouteHandlerDispatchPath)}); +let __dispatchAppRouteHandlerFn; +const __loadAppRouteHandlerDispatch = async () => { + if (__dispatchAppRouteHandlerFn) return __dispatchAppRouteHandlerFn; + const { dispatchAppRouteHandler } = await import(${JSON.stringify(appRouteHandlerDispatchPath)}); + __dispatchAppRouteHandlerFn = dispatchAppRouteHandler; + return __dispatchAppRouteHandlerFn; +}; ${ hasServerActions ? `const __loadAppServerActionExecution = () => import(${JSON.stringify(appServerActionExecutionPath)});` @@ -947,8 +953,8 @@ export default createAppRscHandler({ route, searchParams, }) { - const { dispatchAppRouteHandler: __dispatchAppRouteHandler } = - await __loadAppRouteHandlerDispatch(); + const __dispatchAppRouteHandler = + __dispatchAppRouteHandlerFn ?? (await __loadAppRouteHandlerDispatch()); return __dispatchAppRouteHandler({ basePath: __basePath, cleanPathname, diff --git a/tests/entry-templates.test.ts b/tests/entry-templates.test.ts index 3832411954..1e464b9b32 100644 --- a/tests/entry-templates.test.ts +++ b/tests/entry-templates.test.ts @@ -962,9 +962,13 @@ describe("App Router entry templates", () => { it("generateRscEntry defers route-handler and server-action runtimes", () => { const code = generateRscEntry("/tmp/test/app", minimalAppRoutes, null, [], null, "", false); - expect(code).toContain('const __loadAppRouteHandlerDispatch = () => import("'); + expect(code).toContain("let __dispatchAppRouteHandlerFn;"); + expect(code).toContain("const __loadAppRouteHandlerDispatch = async () => {"); + expect(code).toContain('const { dispatchAppRouteHandler } = await import("'); expect(code).toContain('const __loadAppServerActionExecution = () => import("'); - expect(code).toContain("await __loadAppRouteHandlerDispatch()"); + expect(code).toContain( + "__dispatchAppRouteHandlerFn ?? (await __loadAppRouteHandlerDispatch())", + ); expect(code).toContain("await __loadAppServerActionExecution()"); expect(code).not.toMatch(/import \{\s*dispatchAppRouteHandler as __dispatchAppRouteHandler,/); expect(code).not.toMatch(