import React from 'react'; interface DynamicOptions> { ssr?: boolean; loading?: React.ComponentType; } export function dynamic>( factory: () => Promise< React.ComponentType | { default: React.ComponentType } | Record >, { ssr = true, loading }: DynamicOptions = {}, ): React.ComponentType { const Component = React.lazy(() => factory().then((mod) => { // Case 1: factory() => import('./SomeModule') - direct import // Case 2: factory() => import('./SomeModule').then(mod => mod.default) - extract default if (typeof mod === 'function') { return { default: mod }; } // Case 3: factory() => import('./SomeModule').then(mod => ({ default: mod.default })) - manual wrap // Case 4: factory() => import('./SomeModule').then(mod => ({ default: mod.Named })) - manual wrap named if (mod && typeof mod === 'object' && 'default' in mod) { const defaultExport = mod.default; // Handle both function components and React component objects (e.g., memo/forwardRef) if (typeof defaultExport === 'function') { return { default: defaultExport as React.ComponentType }; } if (defaultExport && typeof defaultExport === 'object' && '$$typeof' in defaultExport) { return { default: defaultExport as React.ComponentType }; } } // Case 5: factory() => import('./SomeModule').then(mod => mod.Named) - find named export if (mod && typeof mod === 'object') { const modObj = mod as Record; for (const key in modObj) { const value = modObj[key]; if (typeof value === 'function') { return { default: value as React.ComponentType }; } if (value && typeof value === 'object' && '$$typeof' in value) { return { default: value as React.ComponentType }; } } } throw new Error('Dynamic import did not return a valid React component'); }), ); const LoadingComponent: React.ComponentType = loading || (() => null); return (props: TProps) => { const [hasMounted, setHasMounted] = React.useState(false); React.useEffect(() => { setHasMounted(true); }, []); if (ssr) { return ( }> ); } if (!hasMounted) { return ; } return ( }> ); }; }