UNPKG

rwsdk

Version:

Build fast, server-driven webapps on Cloudflare with SSR, RSC, and realtime

34 lines (33 loc) 1.43 kB
import React from "react"; import memoize from "lodash/memoize"; export const loadModule = memoize(async (id) => { if (import.meta.env.VITE_IS_DEV_SERVER) { return await import(/* @vite-ignore */ id); } else { const { useClientLookup } = await import("virtual:use-client-lookup.js"); const moduleFn = useClientLookup[id]; if (!moduleFn) { throw new Error(`(client) No module found for '${id}' in module lookup for "use client" directive`); } return await moduleFn(); } }); // context(justinvdm, 2 Dec 2024): re memoize(): React relies on the same promise instance being returned for the same id export const clientWebpackRequire = memoize(async (id) => { const [file, name] = id.split("#"); const promisedModule = loadModule(file); const promisedComponent = promisedModule.then((module) => module[name]); const didSSR = globalThis.__RWSDK_CONTEXT?.rw?.ssr; if (didSSR) { const awaitedComponent = await promisedComponent; return { [id]: awaitedComponent }; } const { ClientOnly } = await import("./ClientOnly"); const promisedDefault = promisedComponent.then((Component) => ({ default: Component, })); const Lazy = React.lazy(() => promisedDefault); const Wrapped = (props) => React.createElement(ClientOnly, null, React.createElement(Lazy, props)); return { [id]: Wrapped }; });