电子:惰性元素类型必须解析为 class 或函数(在生产模式下)

Electron: Lazy element type must resolve to a class or function (in production mode)

我正在尝试使用电子制作桌面应用程序并做出反应。但是当我使用 React.lazy() 它在生产模式 中不起作用 当我打包应用程序时它只显示一个空屏幕(在开发模式下它总是工作正常)

这是一个错误:

Element type is invalid. Received a promise that resolves to: function(){return l.a.createElement("div",null,l.a.createElement("h1",null,"Simple Component"))}. Lazy element type must resolve to a class or function.

我读了很多文章,但还是没能成功。我尝试了不同的 webpack 配置、electron-packager、electron-builder、bozon - 但没有任何帮助使其与 lazy 一起工作。

我仍然可以在不使用 lazy() 的情况下使它工作,但想弄清楚 lazy() 方法有什么问题。

对于这种情况,我在 github (Electron Lazy Repo) 创建了一个简单的存储库,以便您更轻松地找到所有可用信息。

SimpleComponent.js

import React from 'react'

const SimpleComponent = () => {
    return (
        <div>
            <h1>Simple Component</h1>
        </div>
    )
}

export default SimpleComponent

App.js

 import React from 'react'

//import SimpleComponent from './SimpleComponent';
const SimpleComponent = React.lazy(() => import('./SimpleComponent'));

const loading = (
    <div className="pt-3 text-center">
      <div className="sk-spinner sk-spinner-pulse"></div>
    </div>
  )  

const App = () => {
    return (
        <div className='app'>
            <React.Suspense fallback={loading}>
                <SimpleComponent/>
            </React.Suspense>
        </div>
    )
}

export default App

所以如果 import SimpleComponent from './SimpleComponent'; 它有效,如果 const SimpleComponent = React.lazy(() => import('./SimpleComponent')); - 它在生产模式下显示空白屏幕。

能否请您提出错误的建议以及如何使用 lazy 使其工作?

你认为我必须使用没有 lazy() 的经典导入吗?

,问题出在我用来缩小代码的 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 并使用其他一些缩小插件