Reputation: 115
I want to lazy load all of my top-level components to improve load time. I am using react-on-rails to integrate React and Ruby on Rails. To render the components, I have to register them like so in registration.jsx
:
import ReactOnRails from 'react-on-rails';
import Component1 from '../components/Component1';
import Component2 from '../components/Component2';
ReactOnRails.register({Component1, Component2});
I tried two methods:
import {lazy} from "react";
const Component1 = lazy(() => import("../components/Component1"));
But the browser throws an error...
Uncaught Error: Module build failed: SyntaxError:
.../app/registration.jsx: Unexpected token, expected ";" (20:113)
It seems that I cannot use lazy load in this file. So I tried it in a sub component within Component1. But it still doesn't work.
const SubComponent = lazy(() => import("./SubComponent"));
This returns:
Uncaught ReferenceError: SubComponent is not defined
This seems to be recommended by react-on-rails
(see below), but I got a different error saying react-on-rails cannot find such components.
import ReactOnRails from 'react-on-rails';
import Loadable from "react-loadable";
const loading = () => {
return <div>Loading...</div>;
}
const Component1 = Loadable({
"loader": () => import('../components/Component1'),
"loading": loading
});
import Component2 from '../components/Component2';
ReactOnRails.register({Component1, Component2});
This is the error:
Uncaught ReferenceError: ReactOnRails encountered an error while rendering component: Component1.
Original message: React is not defined
I tried to use it on a sub-component, too. But it just doesn't render it.
import Loadable from "react-loadable";
const loading = () => {
return <div>Loading...</div>;
}
const SubComponent = Loadable({
"loader": () => import("./SubComponent"),
"loading": loading
});
class Component1 extends PureComponent {
render () {
return (
<SubComponent />
)
}
}
But this only returns "loading..."
The only good news is that Webpack is correctly splitting the bundles into smaller bundles based on components, so I think react-loadable
works, but was not rendered correctly.
Is it possible to lazy load components using react-on-rails
? Or am I having a syntax error? It seems that react-on-rails
controls how components are loaded.
Another idea: maybe I should only do lazy loading on subcomponents. But I wonder if this will really help decreasing initial load time. Any thoughts?
Upvotes: 5
Views: 868