Using React.lazy with TypeScript

前端 未结 4 1743
情话喂你
情话喂你 2021-01-08 00:17

I am trying to use React.lazy for code splitting in my TypeScript React app.

All I am doing is changing that line:

import {ScreensProductList} from \         


        
相关标签:
4条回答
  • 2021-01-08 00:30

    You should do export default class {...} from the ./screens/Products/list instead of export class ScreensProductList {...}.

    Or, alternatively, you can do:

    const ScreensProductList = lazy(() =>
      import('./screens/Products/List')
        .then(({ ScreensProductList }) => ({ default: ScreensProductList })),
    );
    
    0 讨论(0)
  • 2021-01-08 00:30

    Another way

    const UsersList = () => (
      ..JSX
    )
    
    export default UsersList as React.FC;
    

    Or in old class components

    class UsersList extends Component {
      render(){
    
      }
    }
    
    
    export default UsersList as React.ComponentType
    

    and while importing using React.lazy

    React.lazy( ()=> import("./UsersList") )
    
    0 讨论(0)
  • 2021-01-08 00:36

    You can create an index.ts file where you can export all your components like in this eg. :

    export {default as YourComponentName} from "./YourComponentName";
    

    After that you can use React.lazy:

    React.lazy(() => import("../components/folder-name-where-the-index-file-is-created").then(({YourComponentName}) => ({default: YourComponentName})))
    
    0 讨论(0)
  • 2021-01-08 00:52

    One option is to add default export in "./screens/Products/List" like that

    export default ScreensProductList;
    

    Second is to change import code to

    const ScreensProductList = React.lazy(() =>
      import("./screens/Products/List").then((module) => ({
        default: module.ScreensProductList,
      }))
    );
    

    Or if you don't mind using an external library you could do:

    import { lazily } from 'react-lazily';
    const { ScreensProductList } = lazily(() => import('./screens/Products/List'));
    
    0 讨论(0)
提交回复
热议问题