Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily disable react-loadable

When using react-loadable, you aren't easily alerted by errors thrown in those async components, like a bad import.

I'd like to be able to disable react-loadable in dev environment (bypass it, and load everything synchronously) and enable it in production, but I don't know how to override react-loadable to make this work:

import Loadable from 'react-loadable';
import LoadingComponent from './Loading';

// My reused loadable component everywhere
// In production
export default options =>
  Loadable({
  loading: LoadingComponent,
  delay: 200,
  ...options,
});

// Ideally a dev version that skips loadable
// In development, without any async import
export default options => options.loader(); // Does not work

Is there a way to do this?

like image 988
Florian Bienefelt Avatar asked Dec 18 '18 19:12

Florian Bienefelt


People also ask

What does loadable do in React?

React Loadable is a library by @jamiebuilds that makes it easy to implement code splitting in React and that embraces React's component model. It accomplish its magic using dynamic imports and webpack automatically splits dynamic imports into separate chunks when bundling.

Is react loadable maintained?

No, React Loadable should not be used anymore, because it is not being maintained. It used to be the recommended way for lazy loading when rendering on the server side, while React. lazy only works on the client side.

Does React do code splitting?

Code splitting is a way to split up your code from a large file into smaller code bundles. These can then be requested on demand or in parallel.


2 Answers

You could try exporting one or the other function based on the running state by doing something like this:

import Loadable from 'react-loadable';
import LoadingComponent from './Loading';

let fn = options => Loadable({
    loading: LoadingComponent,
    delay: 200,
    ...options,
})

if (process.env.NODE_ENV !== 'production') {
    fn = options => Loadable({
         loading: () => null,
    });
}

export default fn;

The loading: () => null option is needed to not render anything.

Now you could use the NODE_ENV environmental variable to load or not load the Loadable.

like image 81
Alex Avatar answered Oct 12 '22 20:10

Alex


The short answer is 'no'. I think you would have to rewrite to much code. You could however set up a dev environment with server side rendering, react-loadable is synchronous when SSR.

Use the argument serverSideRequirePath

This is the example usages from this article

import path from 'path';

const LoadableAnotherComponent = Loadable({
  loader: () => import('./another-component'),
  LoadingComponent: MyLoadingComponent,
  delay: 200,
  serverSideRequirePath: path.join(__dirname, './another-component')
});
like image 28
Robbeoli Avatar answered Oct 12 '22 18:10

Robbeoli