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

Viewed 1513

I am trying to make an desktop app using electron and react. But when I am using React.lazy() it doesn't work in production mode when I package app and it shows just an empty screen (in dev mode it works fine always)

Here is an error:

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.

I read lots of articles but still didn't managed to make it work. I tried different webpack configuration, electron-packager, electron-builder, bozon - but nothing helped to make it work with lazy.

I still can make it work without using lazy() but wanted to figure out what's wrong with lazy() approach.

For this case I created a simple repository at github (Electron Lazy Repo) to let you easier find all available information.

SimpleComponent.js

import React from 'react'

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

export default SimpleComponent

And 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

So If do import SimpleComponent from './SimpleComponent'; it works, if const SimpleComponent = React.lazy(() => import('./SimpleComponent')); - it shows empty screen in production mode.

Comparision

Can you please suggest what can be wrong and how to make it work using lazy?

Do you think I have to use classic import without lazy()?

1 Answers

For me, the issue was with the babel-minify-webpack-plugin which I was using to minify my code. Removing that seemed to fix my isse. My guess is, they were saving function definitions as strings to save space, and using eval somewhere inside its logic. But that's just my guess. Maybe it'll fix it for you as well?

Anyway, the 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 instead. Everything seems to work now, and the build time is also significantly reduced. My advice is, avoid using the babel-minify-webpack-plugin and use some other minification plugin instead

Related