0

I am trying to import a react component with @babel/plugin-syntax-dynamic-import but i can not make it work.

Here is my code in my main componant :

import React from 'react';
import Loadable from 'react-loadable';

const Test = Loadable({
  loader: () => import('./Space').default,
  loading: <div>loading</div>
});

const App = () => <Test />;
export default App;

And my code in my Space component :

import React from 'react';

const Space = () => <h1>hello from space</h1>;

export default Space;

And with this code I get this error : Uncaught TypeError: Cannot read property 'then' of undefined

And this which I put here without knowing if it can help : The above error occurred in the <LoadableComponent> component: react-dom.development.js:17117

Yes i have the @babel/plugin-syntax-dynamic-import installed and added in my babel config file.

Anatole Lucet
  • 1,603
  • 3
  • 24
  • 43
  • 1
    I don't think you need the `.default` after your import statement `import('./Space')`. Also, you should try to use `React.lazy` instead of `react-loadable`. Why use an external library when React supports lazy loading. – Mario Subotic May 09 '19 at 04:10

1 Answers1

2

Ok I solved it by using React.lazy (see @Mario Subotic comment).

Here is my final code:

import React, { lazy, Suspense } from 'react';
import Loadable from 'react-loadable';

const Test = lazy(() => import('./Space'));

const App = () => (
  <Suspense fallback={<div>Loading...</div>}>
    <Test />
  </Suspense>
);
export default App;

Note: apprently have to use Suspense around the component you're lazy loading.

Source: https://github.com/reactjs/reactjs.org/issues/1810

Anatole Lucet
  • 1,603
  • 3
  • 24
  • 43