Storybook for SvelteKit
Storybook for SvelteKit is a framework that makes it easy to develop and test UI components in isolation for SvelteKit applications. It includes:
- 🪄 Zero config
- 🧩 Easily mock many Kit modules
- 🔗 Automatic link handling
- 💫 and more!
Requirements
- SvelteKit ≥ 1.0
- Storybook ≥ 8.0
Getting started
In a project without Storybook
Follow the prompts after running this command in your Sveltekit project's root directory:
npm create storybook@latest
More on getting started with Storybook.
In a project with Storybook
This framework is designed to work with Storybook 7+. If you’re not already using v7, upgrade with this command:
npx storybook@latest upgrade
Automatic migration
When running the upgrade
command above, you should get a prompt asking you to migrate to @storybook/sveltekit
, which should handle everything for you. In case that auto-migration does not work for your project, refer to the manual migration below.
Manual migration
First, install the framework:
npm install --save-dev @storybook/sveltekit
Then, update your .storybook/main.js|ts
to change the framework property:
import { StorybookConfig } from '@storybook/sveltekit';
const config: StorybookConfig = {
// ...
framework: '@storybook/sveltekit', // 👈 Add this
// svelteOptions: { ... }, 👈 Remove this
};
export default config;
Finally, these packages are now either obsolete or part of @storybook/sveltekit
, so you no longer need to depend on them directly. You can remove them (npm uninstall
, yarn remove
, pnpm remove
) from your project:
@storybook/svelte-vite
@storybook/svelte-webpack5
storybook-builder-vite
@storybook/builder-vite
Supported features
All Svelte language features are supported out of the box, as the Storybook framework uses the Svelte compiler directly. However, SvelteKit has some Kit-specific modules that aren't supported. Here's a breakdown of what will and will not work within Storybook:
Module | Status | Note |
---|---|---|
$app/environment | ✅ Supported | version is always empty in Storybook. |
$app/forms | ⚠️ Experimental | See How to mock. |
$app/navigation | ⚠️ Experimental | See How to mock. |
$app/paths | ✅ Supported | Requires SvelteKit 1.4.0 or newer. |
$app/stores | ⚠️ Experimental | See How to mock. |
$env/dynamic/public | 🚧 Partially supported | Only supported in development mode. Storybook is built as a static app with no server-side API, so it cannot dynamically serve content. |
$env/static/public | ✅ Supported | |
$lib | ✅ Supported | |
@sveltejs/kit/* | ✅ Supported | |
$env/dynamic/private | ⛔ Not supported | This is a server-side feature, and Storybook renders all components on the client. |
$env/static/private | ⛔ Not supported | This is a server-side feature, and Storybook renders all components on the client. |
$service-worker | ⛔ Not supported | This is a service worker feature, which does not apply to Storybook. |
How to mock
To mock a SvelteKit import you can define it within parameters.sveltekit_experimental
:
export const MyStory = {
parameters: {
sveltekit_experimental: {
stores: {
page: {
data: {
test: 'passed',
},
},
navigating: {
route: {
id: '/storybook',
},
},
updated: true,
},
},
},
};
The available parameters are documented in the API section, below.
Mocking links
The default link-handling behavior (e.g., when clicking an <a href="..." />
element) is to log an action to the Actions panel.
You can override this by assigning an object to parameters.sveltekit_experimental.hrefs
, where the keys are strings representing an href, and the values define your mock. For example:
export const MyStory = {
parameters: {
sveltekit_experimental: {
hrefs: {
'/basic-href': (to, event) => {
console.log(to, event);
},
'/root.*': {
callback: (to, event) => {
console.log(to, event);
},
asRegex: true,
},
},
},
},
};
See the API reference for more information.
Writing native Svelte stories
Storybook provides a Svelte addon maintained by the community, enabling you to write stories for your Svelte components using the template syntax.
The community actively maintains the Svelte CSF addon but still lacks some features currently available in the official Storybook Svelte framework support. For more information, see the addon's documentation.
Setup
If you initialized your project with the Sveltekit framework, the addon has already been installed and configured for you. However, if you're migrating from a previous version, you'll need to take additional steps to enable this feature.
Run the following command to install the addon.
npx storybook@latest add @storybook/addon-svelte-csf
The CLI's add
command automates the addon's installation and setup. To install it manually, see our documentation on how to install addons.
Update your Storybook configuration file (i.e., .storybook/main.js|ts
) to enable support for this format.
// Replace your-framework with the name of your Svelte framework
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
stories: ['../src/**/*.stories.@(js|jsx|ts|tsx|svelte)'],
addons: [
// Other Storybook addons
'@storybook/addon-svelte-csf',
],
};
export default config;
Configure
By default, the Svelte addon addon offers zero-config support for Storybook's SvelteKit framework. However, you can extend your Storybook configuration file (i.e., .storybook/main.js|ts
) and provide additional addon options. Listed below are the available options and examples of how to use them.
// Replace your-framework with the name of your Svelte framework
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
// Other configuration
addons: [
{
name: '@storybook/addon-svelte-csf',
options: {
legacyTemplate: true, // Enables the legacy template syntax
},
},
],
};
export default config;
Options | Description |
---|---|
legacyTemplate | Enables support for the Template component for backward compatibility. options: { legacyTemplate: true } |
Enabling the legacyTemplate
option can introduce a performance overhead and should be used cautiously. For more information, refer to the addon's documentation.
Upgrade to Svelte CSF addon v5
With the Svelte 5 release, Storybook's Svelte CSF addon has been updated to support the new features. This guide will help you migrate to the latest version of the addon. Below is an overview of the major changes in version 5.0 and the steps needed to upgrade your project.
Simplified story API
If you are using the Meta
component or the meta
named export to define the story's metadata (e.g., parameters), you'll need to update your stories to use the new defineMeta
function. This function returns an object with the required information, including a Story
component that you must use to define your component stories.
<script>
import { Meta, Story } from '@storybook/addon-svelte-csf';
import MyComponent from './MyComponent.svelte';
</script>
<Meta title="MyComponent" component={MyComponent} />
<Story name="Default" />
Story templates
If you used the Template
component to control how the component renders in the Storybook, this feature was replaced with built-in children support in the Story
component, enabling you to compose components and define the UI structure directly in the story.
<script>
import { Meta, Template, Story } from '@storybook/addon-svelte-csf';
import OuterComponent from './OuterComponent.svelte';
import MyComponent from './MyComponent.svelte';
</script>
<Meta title="MyComponent" component={MyComponent} />
<Template let:args>
<OuterComponent>
<MyComponent />
</OuterComponent>
</Template>
<Story name="Default" />
If you need support for the Template
component, the addon provides a feature flag for backward compatibility. For more information, see the configuration options.
Story slots to snippets
With Svelte's slot deprecation and the introduction of reusable snippets
, the addon also introduced support for this feature allowing you to extend the Story
component and provide a custom snippet to provide dynamic content to your stories. This feature extends the built-in children
support in the Story
component, allowing you to create dynamic stories without losing reactivity.
<script>
import { defineMeta } from '@storybook/addon-svelte-csf';
import MyComponent from './MyComponent.svelte';
const { Story } = defineMeta({
component: MyComponent,
});
</script>
<Story name="Default" args={{ exampleProperty: true }}>
{#snippet children(args)}
<MyComponent {...args}>Reactive component</MyComponent>
{/snippet}
</Story>
Tags support
If you enabled automatic documentation generation with the autodocs
story property, you must replace it with tags
. This property allows you to categorize and filter stories based on specific criteria and generate documentation based on the tags applied to the stories.
<script>
import { Meta, Template, Story } from '@storybook/addon-svelte-csf';
import MyComponent from './MyComponent.svelte';
</script>
<Meta title="MyComponent" component={MyComponent} />
<Template let:args>
<MyComponent {...args} />
</Template>
<Story name="Default" autodocs />
API
Parameters
This framework contributes the following parameters to Storybook, under the sveltekit_experimental
namespace:
forms
Type: { enhance: () => void }
Provides mocks for the $app/forms
module.
forms.enhance
Type: () => void
A callback that will be called when a form with use:enhance
is submitted.
hrefs
Type: Record<[path: string], (to: string, event: MouseEvent) => void | { callback: (to: string, event: MouseEvent) => void, asRegex?: boolean }>
If you have an <a />
tag inside your code with the href
attribute that matches one or more of the links defined (treated as regex based if the asRegex
property is true
) the corresponding callback
will be called. If no matching hrefs
are defined, an action will be logged to the Actions panel. See Mocking links for an example.
navigation
Type: See SvelteKit docs
Provides mocks for the $app/navigation
module.
navigation.goto
Type: See SvelteKit docs
A callback that will be called whenever goto
is called. If no function is provided, an action will be logged to the Actions panel.
navigation.pushState
Type: See SvelteKit docs
A callback that will be called whenever pushState
is called. If no function is provided, an action will be logged to the Actions panel.
navigation.replaceState
Type: See SvelteKit docs
A callback that will be called whenever replaceState
is called. If no function is provided, an action will be logged to the Actions panel.
navigation.invalidate
Type: See SvelteKit docs
A callback that will be called whenever invalidate
is called. If no function is provided, an action will be logged to the Actions panel.
navigation.invalidateAll
Type: See SvelteKit docs
A callback that will be called whenever invalidateAll
is called. If no function is provided, an action will be logged to the Actions panel.
navigation.afterNavigate
Type: See SvelteKit docs
An object that will be passed to the afterNavigate
function, which will be invoked when the onMount
event fires.
stores
Type: See SvelteKit docs
Provides mocks for the $app/stores
module.
stores.navigating
Type: See SvelteKit docs
A partial version of the navigating
store.
stores.page
Type: See SvelteKit docs
A partial version of the page
store.
stores.updated
Type: boolean
A boolean representing the value of updated
(you can also access updated.check()
which will be a no-op).
Options
You can pass an options object for additional configuration if needed:
import { StorybookConfig } from '@storybook/sveltekit';
const config: StorybookConfig = {
// ...
framework: {
name: '@storybook/sveltekit',
options: {
// ...
},
},
};
export default config;
The available options are:
builder
Type: Record<string, any>
Configure options for the framework's builder. For Sveltekit, available options can be found in the Vite builder docs.
Troubleshooting
Error when starting Storybook
When starting Storybook after upgrading to v7.0, it may quit with the following error:
ERR! SyntaxError: Identifier '__esbuild_register_import_meta_url__' has already been declared
This can occur when manually upgrading from 6.5 to 7.0. To resolve it, you'll need to remove the svelteOptions
property in .storybook/main.js
, as that is not supported (and no longer necessary) in Storybook 7+ with SvelteKit.