Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[Incubation] CSF using Svelte components.

License

NotificationsYou must be signed in to change notification settings

storybookjs/addon-svelte-csf

Repository files navigation

This Storybook addon allows you to write Storybook stories using the Svelte language instead of ESM that regular CSF is based on.

npx storybook@latest add @storybook/addon-svelte-csf

Using the Svelte language makes it easier to write stories for composed components that rely on snippets or slots, which aren't easily re-created outside of Svelte files.

🐣 Getting Started

Tip

If you've initialized your Storybook project with Storybook version 8.2.0 or above, this addon is already set up for you!

Important

Not running the latest and greatest versions of Storybook or Svelte? Be sure to checkthe version compatibility section below.

The easiest way to install the addon is withstorybook add:

npx storybook@latest add @storybook/addon-svelte-csf

You can also add the addon manually. First, install the package:

npm install --save-dev @storybook/addon-svelte-csf

Then modify yourmain.ts Storybook configuration to include the addon and include*.stories.svelte files:

export default {-  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)',+  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx|svelte)'],  addons: [+    '@storybook/addon-svelte-csf',    ...  ],  ...}

Restart your Storybook server for the changes to take effect.

🐓 Usage

Note

The documentation here does not cover all of Storybook's features, only the aspects that are specific to the addon and Svelte CSF. We recommend that you familiarize yourself with Storybook's core concepts athttps://storybook.js.org/docs.

Theexamples directory contains examples describing each feature of the addon. TheButton.stories.svelte example is a good one to get started with.The Storybook with all the examples is published on Chromatic here.

Svelte CSF stories files must always have the.stories.svelte extension.

Defining the meta

All stories files must have a "meta" (aka. "default export") defined, and its structure follows what's described inthe official docs on the subject. To define the meta in Svelte CSF, call thedefineMeta functionwithin the module context, with the meta properties you want:

<scriptmodule>//    👆 notice the module context, defineMeta does not work in a regular <script> tag - instanceimport {defineMeta }from'@storybook/addon-svelte-csf';importMyComponentfrom'./MyComponent.svelte';//      👇 Get the Story component from the return valueconst {Story }=defineMeta({    title:'Path/To/MyComponent',    component: MyComponent,    decorators: [/* ...*/    ],    parameters: {/* ...*/    },  });</script>

defineMeta returns an object with aStory component (seeDefining stories below) that you must destructure out to use.

Defining stories

To define stories, you use theStory component returned from thedefineMeta function. Depending on what you want the story to contain,there are multiple ways to use theStory component. Common for all the use case is that all properties ofa regular CSF story are passed as props to theStory component, with the exception of therender function, which does not have any effect in Svelte CSF.

All story requires either thename prop orexportName prop.

Tip

In versions prior to v5 of this addon, it was always required to define a template story with the<Template> component. This is no longer required and stories will default to render the component frommeta if no template is set.

Plain Story

If your component only accepts props and doesn't require snippets or slots, you can use the simple form of defining stories, only using args:

<Storyname="Primary"args={{primary:true }} />

This will render the component defined in the meta, with the args passed as props.

With children

If your component needs children, you can pass them in directly to the story, and they will be forwarded to your component:

<Storyname="With Children">I will be the child of the component from defineMeta</Story>

Static template

If you need more customization of the story, like composing components or defining snippets, you can set theasChild prop on the Story. Instead of forwarding the children to your component, it will instead use the children directly as the story output. This allows you to write whatever component structure you desire:

<Storyname="Composed"asChild>  <MyComponent>    <AChildlabel="Hello world!" />  </MyComponent></Story>

Important

This format completely ignores args, as they are not passed down to any of the child components defined. Even if your story has args and Controls, they won't have an effect. See the snippet-based formats below.

Inline snippet

If you need composition/snippets but also want a dynamic story that reacts to args or the story context, you can define atemplate snippet in theStory component:

<Storyname="Simple Template"args={{simpleChild:true }}>  {#snippettemplate(args)}    <MyComponent {...args}>Component with args</MyComponent>  {/snippet}</Story>

Shared snippet

Often your stories are very similar and their only differences are args or play-functions. In this case it can be cumbersome to define the sametemplate snippet over and over again. You can share snippets by defining them at the top-level and passing them as props toStory:

{#snippettemplate(args)}  <MyComponent {...args}>    {#ifargs.simpleChild}      <AChilddata={args.childProps} />    {:else}      <ComplexChildAdata={args.childProps} />      <ComplexChildBdata={args.childProps} />    {/if}  </MyComponent>{/snippet}<Storyname="Simple Template"args={{simpleChild:true }} {template} /><Storyname="Complex Template"args={{simpleChild:false }} {template} />

You can also use this pattern to define multiple templates and share the different templates among different stories.

Default snippet

If you only need a single template that you want to share, it can be tedious to include{template} in eachStory component. Like in th example below:

<Storyname="Primary"args={{variant:'primary' }} {template} /><Storyname="Secondary"args={{variant:'secondary' }} {template} /><Storyname="Tertiary"args={{variant:'tertiary' }} {template} /><!-- ... more ... --><Storyname="Denary"args={{variant:'denary' }} {template} />

Similar to regular CSF, you can define a meta-levelrender-function, by referencing your default snippet in therender property of yourdefineMeta call:

<scriptmodule>import {defineMeta }from'@storybook/addon-svelte-csf';importMyComponentfrom'./MyComponent.svelte';const {Story }=defineMeta({    render: template,//      👆 the name of the snippet as defined below (can be any name)  });</script>{#snippettemplate(args)}  <MyComponent {...args}>    {#ifargs.simpleChild}      <AChilddata={args.childProps} />    {:else}      <ComplexChildAdata={args.childProps} />      <ComplexChildBdata={args.childProps} />    {/if}  </MyComponent>{/snippet}<Storyname="Simple Children"args={{simpleChild:true }} /><Storyname="Complex Children"args={{simpleChild:false }} />

Stories can still override this default snippet using any of the methods for defining story-level content.

Note

Svelte has the limitation, that you can't reference a snippet from a<script module> if it reference any declarations in a non-module<script> (whether directly or indirectly, via other snippets). Seesvelte.dev/docs/svelte/snippet#Exporting-snippets

Custom export name

Behind-the-scenes, each<Story /> definition is compiled to a variable export likeexport const MyStory = ...;. In most cases you don't have to care about this detail, however sometimes naming conflicts can arise from this. The variable names are simplifications of the story names - to make them valid JavaScript variables.

This can cause conflicts, eg. two stories with the names"my story!" and"My Story" will both be simplified toMyStory.

You can explicitly define the variable name of any story by passing theexportName prop:

<StoryexportName="MyStory1"name="my story!" /><StoryexportName="MyStory2"name="My Story" />

At least one of thename orexportName props must be passed to theStory component - passing both is also valid.

Accessing Story context

If for some reason you need to access theStory context(e.g. for mocking) while rendering the story, then<Story />'s attributetemplate snippet provides an optional second argument.

<Storyname="Default">  {#snippettemplate(args,context)}<!--                    👆 use the optional second argument to access Story context -->     <MyComponent {...args}>  {/snippet}</Story>

TypeScript

Story template snippets can be type-safe when necessary. The type of the args are inferred from thecomponent orrender property passed todefineMeta.

If you're just rendering the component directly without a custom template, you can use Svelte'sComponentProps type andStoryContext from the addon to make your template snippet type-safe:

<scriptmodulelang="ts">import {defineMeta,typeStoryContext }from'@storybook/addon-svelte-csf';import {typeComponentProps }from'svelte';importMyComponentfrom'./MyComponent.svelte';const { Story }=defineMeta({    component:MyComponent,  });typeArgs=ComponentProps<MyComponent>;</script>{#snippettemplate(args:Args,context:StoryContext<typeofLayout>)}  <MyComponent {...args} />{/snippet}

If you use therender-property to define a custom template that might use custom args, the args will be inferred from the types of the snippet passed torender. This is especially useful when you're converting primitive args to snippets:

<scriptmodulelang="ts">import {defineMeta,typeStoryContext }from'@storybook/addon-svelte-csf';import {typeComponentProps }from'svelte';importMyComponentfrom'./MyComponent.svelte';const { Story }=defineMeta({    component:MyComponent,    render:template,// 👈 args will be inferred from this, which is the Args type below    argTypes: {      children: {        control:'text',      },      footer: {        control:'text',      },    },  });typeArgs=Omit<ComponentProps<MyComponent>,'children'|'footer'>& {    children:string;    footer?:string;  };// OR use the Merge helper from the 'type-fest' package:typeArgs=Merge<ComponentProps<MyComponent>,    {      children:string;      footer?:string;    }  >;</script><!--                👇 you need to omit 'children' from args to satisfy Svelte's constraints -->{#snippettemplate({children,...args }:Args,context:StoryContext<typeofMyComponent>)}  <MyComponent {...args}>    {children}    {#snippetfooter()}      {args.footer}    {/snippet}  </MyComponent>{/snippet}

SeetheTypes.stories.svelte examples on how to use complex types properly.

Legacy API

Version 5 of the addon changes the API from v4 in key areas, as described above. However a feature flag has been introduced to maintain support for the<Template>-based legacy API as it was prior to v5.

To enable supoprt for the legacy API, make the following change to your main Storybook config:

export default {  addons: [-    '@storybook/addon-svelte-csf',+    {+      name: '@storybook/addon-svelte-csf',+      options: {+         legacyTemplate: true+    },    ...  ],  ...}

This can make the overall experience slower, because it adds more transformation steps on top of the existing ones. It should only be used temporarily while migrating to the new API. It's highly likely that the legacy support will be dropped in future major versions of the addon.

The legacy support is not bullet-proof, and it might not work in all scenarios that previously worked. If you're experiencing issues or getting errors after upgrading to v5, try migrating the problematic stories files to the modern API.

Version compatibility

latest

Version 5 and up of this addon requiresat least:

DependencyVersion
Storybookv8.0.0
Sveltev5.0.0
Vitev5.0.0
@sveltejs/vite-plugin-sveltev4.0.0

Important

As ofv5 this addon does not support Webpack.

v4

npm install --save-dev @storybook/addon-svelte-csf@^4

Version 4 of this addon requiresat least:

  • Storybook v7
  • Svelte v4
  • Vite v4 (if using Vite)
  • @sveltejs/vite-plugin-svelte v2 (if using Vite)

v3

npm install --save-dev @storybook/addon-svelte-csf@^3

Version 3 of this addon requiresat least:

  • Storybook v7
  • Svelte v3

v2

npm install --save-dev @storybook/addon-svelte-csf@^2

If you're using Storybook between v6.4.20 and v7.0.0, you should use version^2.0.0 of this addon.

🤝 Contributing

This project usespnpm for dependency management.

  1. Install dependencies withpnpm install
  2. Concurrently start the compilation and the internal Storybook withpnpm start.
  3. Restarting the internal Storybook is often needed for changes to take effect.

[8]ページ先頭

©2009-2025 Movatter.jp