In my project, I am looking to manually implement code-splitting with preact. While preact already handles code splitting for routes, I want to take control of it.
The scenario is that I am creating a tool where users can customize widgets on a dashboard. I only want to load the code for the widgets that the user has configured on the home page, not all available widgets.
Therefore, I prefer not to bundle the code for all widgets in a single bundle.js file but instead load it lazily when required, such as when rendering the list of widgets.
I tried using the async!
syntax, which I found in older commits for the boilerplate, but it didn't work as expected.
Here is a simplified version of the code I am working with
Configuration data
[{ "type": "notes", "title": "Widget 1}, { "type": "todo", "title": "Widget 2"}]
The render function for the widget list
const Grid = ({ widgets }) => (
<ul>
{widgets.map((widget) => <li key={widget.title}><Widget widget={widget} /></li>)}
</ul>
);
Widget component structure
Here I have defined a mapping from the widget type to its corresponding component:
import notes from widgets/notes;
import todo from widgets/todo;
class Widget extends Component {
widgetMap(widget) {
if (widget.type === 'notes') {
return notes;
}
if (widget.type === 'todo') {
return todo;
}
}
render ({ widget }) {
const widgetComponent = this.widgetMap(map);
return (
<div>
<h1>{widget.title}</h1>
<widgetComponent />
</div>
);
}
}