React.lazy在生产模式下无法使用。

7

我有一个运行中的React应用程序,我想使用React.lazy实现基于路由的代码分割。

目前我的代码是这样的:

import { PureComponent, cloneElement, Suspense, lazy } from 'react';
...
export const CartPage = lazy(() => import(/* webpackMode: "lazy", webpackPrefetch: true */ 'Route/CartPage'));
...
<Suspense fallback={ this.renderFallbackPage() }>
    <NoMatchHandler>
       <Switch>
          ...
             <Route path="/cart" exact component={ CartPage } />
          ...
       </Switch>
    </NoMatchHandler>
</Suspense>

这里只列出相关部分以使其更紧凑。

现在的问题是,在webpack-dev-server中运行得非常完美,但当我运行npm run build并转到/cart时,代码就会崩溃。按照链接中提到的,这是错误信息:

Element type is invalid. Received a promise that resolves to: function i(e){var r;return
r=t.call(this,e)||this,T()(y?!e.wrapperProps[d]:!e[d],"Passing redux store in props has
been removed and does not do anything.
"+P),r.selectDerivedProps=n(),r.selectChildElement=function(){var t,e,n,r;return
function(i,o,a){return(o!==t||a!==e||r!==i)&&(t=o,e=a,r=i,n=m.a.createElement(i,Object(O.a)
({},o,{ref:a}))),n}}
(),r.indirectRenderWrappedComponent=r.indirectRenderWrappedComponent.bind(function(t)
{if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been 
called");return t}(r)),r}. Lazy element type must resolve to a class or function.

我已经完成了一些常见的故障排除:

  1. CartPage组件中,我已经执行了export default connect(mapStateToProps, mapDispatchToProps)(CartPage);
  2. React版本为16.13.1

奇怪的是,Received a promise that resolves to: function...。它是一个函数!但是它却抱怨Lazy element type must resolve to a class or function。这对我来说毫无意义。

可能出了什么问题?

编辑

Route/CartPage/index.js有以下内容:

import { PureComponent } from 'react';

export default class CartPage extends PureComponent {
     render() {
         return <h1>Test</h1>;
     }
}

我特意尽可能地让它变得简单。但是还是出现了相同的错误。但是参数不同。现在的错误是 this

Element type is invalid. Received a promise that resolves to: function
t(){return c()(this,t),r.apply(this,arguments)}. Lazy element type 
must resolve to a class or function.

编辑2

我从我的webpack.config.js中删除了以下行。然后它开始工作!但还是不知道为什么。

const MinifyPlugin = require('babel-minify-webpack-plugin');
...    
plugins: [
    ...,
    new MinifyPlugin({
        removeConsole: false,
        removeDebugger: false
    }, {
        comments: false
    })
]
...

你找到任何解决方案了吗?我也有同样的问题。 - Ivan Salo
不是这个问题。奇怪的是,我安装了一个全新的React,React.lazy在那里运行得很好。不确定我在项目中做错了什么。 - Jay Ghosh
在这个文件中,您应该使用默认导出(default export) - nickbullock
是的,如果这是路由问题,那就很有趣了。 - felixmosh
让我们在聊天中继续这个讨论 - Jay Ghosh
显示剩余10条评论
1个回答

4

如我在问题中提到的,babel-minify-webpack-plugin 由于某些原因造成了问题。我猜想他们将函数定义保存为字符串以节省空间,并在其逻辑的某个地方使用了 eval。但这只是我的猜测。

无论如何,babel-minify-webpack-plugin 的 Github 页面表明它已被弃用,所以我最终从我的项目中删除了它,并使用terser-webpack-plugin代替它。现在一切似乎都正常工作了,并且构建时间也显著缩短了。我的建议是避免使用 babel-minify-webpack-plugin ,而是使用其他缩小插件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接