React.lazy 在生产模式下不工作

React.lazy not working in production mode

我有一个 React 应用 运行ning,我想使用 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 运行 build 并转到 /cart代码中断。关注了link mentioned for the error之后,就是这条消息

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
    })
]
...

就像我在问题中提到的,babel-minify-webpack-plugin 是出于某种原因导致了这个问题。我的猜测是,他们将函数定义保存为字符串以保存 space,并在其逻辑中的某处使用 eval。但这只是我的猜测。

无论如何, Github page for babel-minify-webpack-plugin says that it is deprecated, so I ended up removing that from my project, and using the terser-webpack-plugin 代替。现在似乎一切正常,构建时间也大大减少了。我的建议是,避免使用 babel-minify-webpack-plugin 并使用其他一些缩小插件