36 lines
1.1 KiB
JavaScript
36 lines
1.1 KiB
JavaScript
import { lazy } from "react";
|
|
|
|
/**
|
|
* Conditionally uses lazy loading based on environment.
|
|
* By default, uses React.lazy in all environments.
|
|
* Set VITE_DISABLE_LAZY_LOADING=true to load modules immediately in development (avoids compilation delays).
|
|
*
|
|
* Usage: const MyComponent = lazyDev(() => import('./MyComponent'));
|
|
*/
|
|
export const lazyDev = (importFunc) => {
|
|
// Check if lazy loading should be disabled (dev only, opt-in via env var)
|
|
const disableLazyLoading = import.meta.env.DEV && import.meta.env?.VITE_DISABLE_LAZY_LOADING === "true";
|
|
|
|
if (!disableLazyLoading) {
|
|
// Default behavior: use React.lazy for code splitting
|
|
return lazy(importFunc);
|
|
}
|
|
|
|
// Dev mode with lazy loading disabled: load immediately to avoid delays
|
|
let Component = null;
|
|
const promise = importFunc().then((module) => {
|
|
Component = module.default;
|
|
});
|
|
|
|
const LazyDevComponent = (props) => {
|
|
if (!Component) {
|
|
throw promise; // Suspense will catch this
|
|
}
|
|
return <Component {...props} />;
|
|
};
|
|
|
|
LazyDevComponent.displayName = "LazyDevComponent";
|
|
|
|
return LazyDevComponent;
|
|
};
|