Skip to content

Instantly share code, notes, and snippets.

@alibek-gao
Last active April 24, 2023 15:56
Show Gist options
  • Save alibek-gao/48d2109b86b0018bb014dda206e4a458 to your computer and use it in GitHub Desktop.
Save alibek-gao/48d2109b86b0018bb014dda206e4a458 to your computer and use it in GitHub Desktop.
attempt to implement dynamic remote with dynamic routes
import { useMemo } from 'react'
import { injectScript } from '@module-federation/utilities'
import dynamic from 'next/dynamic'
// TODO: replace with a LRU cache or something similar
const remotePagesMap = new Map();
function DynamicComponent({ remote, path, props }) {
const Component = useMemo(() => {
if (typeof window === 'undefined') {
// if wrap this in a dynamic(), it doesn't render on the server
// return dynamic(() => Promise.resolve(remotePagesMap.get(path)), { ssr: true });
return remotePagesMap.get(path);
}
return dynamic(() => {
return injectScript(remote)
.then(container => container.get(`.${path}`))
.then(factory => factory())
}, {
ssr: true,
// TODO: how to prevent hydration before Component is loaded?
loading: () => null,
})
}, [remote, path]);
return <Component {...props} />;
}
export function Page({ path, props }) {
return <DynamicComponent remote="shop" path={path} props={props} />;
}
export const getServerSideProps = async (ctx) => {
const path = ctx.resolvedUrl.split('?')[0];
const container = await injectScript('shop');
const remote = await container.get(`.${path}`)
.then((factory) => factory());
remotePagesMap.set(path, remote.default);
const props = (await remote.getServerSideProps(ctx)).props;
return { props: { path, props } }
}
export default Page;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment