简体   繁体   中英

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

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…

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM