Skip to content

Instantly share code, notes, and snippets.

@jrson83
Forked from goran-peoski-work/lazy.ts
Created April 13, 2024 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrson83/7d6c0f91d1b0d0316c36793baa54a548 to your computer and use it in GitHub Desktop.
Save jrson83/7d6c0f91d1b0d0316c36793baa54a548 to your computer and use it in GitHub Desktop.
Dynamic import of omponent
import React, { ComponentType, LazyExoticComponent } from "react";
type Transformer = <T>(name: keyof T) => (module: T) => { default: T[keyof T] };
const transformer: Transformer = (
(name) => (module) => ({ default: module[name] })
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type LazyImport = <T extends ComponentType<any>>(path: string, name: string) => LazyExoticComponent<T>;
export const lazyImport: LazyImport = (
(path, name) => React.lazy(
() => import(path).then(transformer(name))
)
);
const Admin = lazyImport("pages/Admin/Admin", "Admin")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment