1

使用代码拆分后,我无法找到如何在我的 React 应用程序中导入类。

之前(它有效!):

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... */ 
 }

使用代码拆分后(不起作用):

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... */ 
 }

使用代码拆分后出现此错误

TypeError:需要一个插件类,但得到了对象。请验证插件是否已导入且拼写正确。

当我控制台.log

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

我明白了:

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

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

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

2 回答 2

2

似乎在您的工作示例中(在代码拆分之前),您正在从“./components/test”导入默认导出。

在您动态import地允许代码拆分之后,您应该使用Tus.default来实现相同的结果。您可以在webpack 代码拆分文档中阅读更多相关信息。

换句话说,import('./component/test').then(Tus => Tus.default)

我希望这有帮助!干杯!

于 2018-08-31T11:58:37.247 回答
0

您也可以使用react-loadable它为您提供加载组件后备:

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

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

在您的路线中:

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

你应该已经安装了:在你的package.json

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

在 .babelrc

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

它工作得很好。

于 2018-08-31T13:18:04.287 回答