Load local Blok components automatically #1016
Labels
enhancement
[Issue][PR] New feature
pending-author
[Issue] Awaiting further information or action from the issue author
pending-triage
[Issue] Ticket is pending to be prioritised
Description
I would like the SDK to offer an option to automatically register components. Having to maintain a mapping manually feels like a step back, when all the required building bloks (ha!) are already present.
Suggested solution or improvement
So, I actually built this already, and if it won't make it into the SDK itself, maybe you'd want to add it to the tutorial, or at least leave it here for others to copy.
To register components automatically, we can use a custom Vite plugin that provides a virtual module that serves as a barrel file for all Storyblok components.
The Vite plugin
Create a new, local Vite plugin in your
src
directory (I keep them insrc/build/
):vite-plugin-storyblok-components.ts
Configuring Vite
Now, we can add that plugin to the Vite configuration in
vite.config.ts
:The plugin takes the path to your Storyblok components, and expects to find Svelte components named like the Blok. So, for example, if you use the default Bloks:
teaser
teaser.svelte
src/lib/components/Storyblok/teaser.svelte
grid
grid.svelte
src/lib/components/Storyblok/grid.svelte
Page
Page.svelte
src/lib/components/Storyblok/Page.svelte
nested
nested.svelte
src/lib/components/Storyblok/some/sub/dir/nested.svelte
Importing the components
Now that we've added the plugins, we can import the virtual module with our components and pass it to the Storyblok client:
Done. Now you can simply use all components that exist in your Storyblok folder, without having to register them manually. The folder will be checked recursively, so you can maintain any structure within it you like. This could certainly be improved further (loading components from the API, checking for changes, integrating with TypeScript types out of the box, etc.), but it's a good start.
I'd love to see a simple Storyblok Vite plugin that handled this by itself, however. The process really isn't complicated, and makes the DX a lot cleaner IMO.
Additional context
No response
Validations
The text was updated successfully, but these errors were encountered: