Reputation: 557
I am trying to make my application more performant with React.lazy. As the Ethereum lightwallet is a huge file, I would like to put it into a separate bundle. The currently working import is the following:
import lightwallet from 'eth-lightwallet/dist/lightwallet.min.js';
When I try to import using the lazy syntax
const lightwallet = React.lazy(() => import('eth-lightwallet/dist/lightwallet.min.js'));
Only a React.lazy object ($$typeof: Symbol(react.lazy)) is returned instead of the lightwallet object. I think this is due to the fact that lightwallet doesn't have a default export. How could I get around this problem? Thanks!
Upvotes: 7
Views: 11267
Reputation: 2587
I suggest following the example here:
https://reacttraining.com/react-router/web/guides/code-splitting
react-loadable
is an npm package that makes code-splitting (a.k.a lazy loading) quite easy and also provides you the ability to render a loading component until the lazy load has finished.
The only gotcha is that if you're using Babel
to transpile your code bundles, you'll have to add support for the Dynamic Import syntax, webpack
already has this by default, but Babel
doesn't.
The Babel Plugin:
@babel/plugin-syntax-dynamic-import
will make this possible by adding support for the syntax.
I recommend react-loadable
over React.lazy
as it makes displaying a loading component while the lazy-load happens VERY easy, and provides you hooks to display an error component and retry the import in the case that it fails.
Read more about react-loadable
here:
https://github.com/jamiebuilds/react-loadable
Your code would look something like this:
import Loadable from 'react-loadable';
import Loading from './YOUR-LOADING-COMPONENT';
const LoadableWallet = Loadable({
loader: () => import('eth-lightwallet/dist/lightwallet.min.js'),
loading: Loading,
});
export default class Wallet extends React.Component {
render() {
return <LoadableWallet/>;
}
}
Upvotes: 5
Reputation: 576
Make sure that your react version is up to date in React v16.6.0. And also the core idea behind the React. lazy is React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component. But is this scenario min.js won't give any promise. Most probably That didn't work.
Upvotes: 4