how to import a class in code splitting using import()?

475 Views Asked by At

I cannot find out how to import a class in my React app after using the code splitting.

Before (it works!):

import React, {PureComponent} from 'react';
import Tus from './components/test';

 class Shopper extends PureComponent {
    constructor (props) {
    super(props); }

  uploadModal () { 

/* some function code... */

   .use(Tus, { 
        endpoint: 'http://192.168.22.124:3000/upload/'
    })
  /* more codes... */ 
 }

After using code splitting (does not work):

import React, {PureComponent} from 'react';

 class Shopper extends PureComponent {   
    constructor (props) {
    super(props); }

  uploadModal () { 

/* some function code... */

   .use(import('./components/test').then(Tus => Tus, { 
        endpoint: 'http://192.168.22.124:3000/upload/'
    })
  /* more codes... */ 
 }

I am getting this error after using code split

TypeError: Expected a plugin class, but got object. Please verify that the plugin was imported and spelled correctly.

When I console.log

import('./component/test').then(Tus => console.log(Tus))

I get this:

ƒ Tus(uppy, opts) {
    _classCallCheck(this, Tus);

    var _this = _possibleConstructorReturn(this, _Plugin.call(this, uppy, opts));

    _this.type = 'uploader';
    _this.id = 'Tus';
    _this.titl…
2

There are 2 best solutions below

2
Thiago Murakami On

It seems that on your working example (before code split), you're importing the default export from `'./components/test'.

After you dynamically import to allow code-splitting, you should use Tus.default to achieve the same result. You can read more about it on webpack code splitting documentation.

In other words, import('./component/test').then(Tus => Tus.default)

I hope this helps! Cheers!

0
Sakhi Mansoor On

You can aslo use react-loadable it provides you loading component fallback:

function Loading() {
  return <div>Loading...</div>;
}

const Test= Loadable({
  loader: () => import('./components/test'),
  loading: Loading,
});

In your route:

 <Route exact path="/" component={Test} />

You should have installed: in your package.json:

"@babel/plugin-syntax-dynamic-import": "7.0.0-beta.54",

in .babelrc

"plugins": [
"@babel/plugin-syntax-dynamic-import",]

It works great.