gregberge / loadable-components

The recommended Code Splitting library for React ✂️✨
https://loadable-components.com
MIT License
7.66k stars 380 forks source link

loadable/component Synchronously Load Component Failed with Error "Cannot convert undefined or null to object #963

Closed yzfdjzwl closed 1 year ago

yzfdjzwl commented 1 year ago

I'm using the loadable/component library for server-side rendering (SSR) in my React application. However, I encountered an error when trying to synchronously load a component.

The error message is:

loadable-components: failed to synchronously load component, which expected to be available {
  fileName: './node_modules/MyComponent/index.tsx',
  chunkName: 'loadable_MyComponent',
  error: 'Cannot convert undefined or null to object'
}

If MyComponent export default MyComponent, it's worked, but if MyComponent only export const MyComponent, it's not work, Here is my usage:

// Bad
// MyComponent.tsx
export const MyComponent = () => <div></div>;

const LoadableMyComponent = loadable(() =>
    import(/* webpackChunkName: "loadable_MyComponent" */ 'MyComponent').then(
        module => ({ default: module.MyComponent }),
    ),
);

// Good
// MyComponent.tsx
const MyComponent = () => <div></div>;
export default  MyComponent;

const LoadableMyComponent = loadable(() =>
    import(/* webpackChunkName: "loadable_MyComponent" */ 'MyComponent'),
);

And I've already set up ChunkExtractor in the server-side code and properly configured loadable/babel-plugin in my Webpack and Babel configurations.

However, when running my application, I received the above error message indicating that loadable/component failed to synchronously load the MyComponent component. This error only occurs when the MyComponent component is inside the loadable function. If I remove MyComponent from the loadable function, the error doesn't occur.

I've checked that the module path is correct and it exports a React component correctly. The loadable-stats.json is also generated and referenced correctly in my application.

I'm looking for guidance to solve this issue. Any help would be greatly appreciated. Thanks.

yzfdjzwl commented 1 year ago
const LoadableMyComponent = loadable(
    () => import(/* webpackChunkName: "loadable_MyComponent" */ 'MyComponent'),
    {
        resolveComponent: components => components.MyComponent,
    },
);

This can work!

theKashey commented 1 year ago

This is expected way to handle named exports 😉