Automatic setup

If you want to set up Storybook manually for your Svelte project, this is the guide for you.

Step 1: Add dependencies

Add @storybook/svelte to your project. To do that, run:

  1. npm install @storybook/svelte --save-dev

@babel/core, and babel-loader

Make sure that you have @babel/core, and babel-loader in your dependencies as well because we list these as a peer dependencies:

  1. npm install babel-loader @babel/core --save-dev

Then add the following NPM script to your package.json in order to start the storybook later in this guide:

Step 3: Create the config file

To do that, create a file at .storybook/config.js with the following content:

  1. import { configure } from '@storybook/svelte';
  2. configure(require.context('../src', true, /\.stories\.js$/), module);

That will load all the stories underneath your ../src directory that match the pattern *.stories.js. We recommend co-locating your stories with your source files, but you can place them wherever you choose.

Now create a ../src/index.stories.js file, and write your first story like this:

  1. import MyButton from '../components/MyButton.svelte';
  2. Component: MyButton,
  3. props: {
  4. buttonText: 'some text',
  5. },
  6. });
  7. export const withEmoji = () => ({
  8. Component: MyButton,
  9. props: {
  10. buttonText: '😀 😎 👍 💯',
  11. },
  12. });

Svelte storybooks don’t support using templates in a story yet.Instead, you can create a .svelte file to compose components together, or simply to access all normal Svelte functionality, like slots.

So you can create a story “view” file, essentially just a .svelte file to load your components into to test.

If your component doesn’t use slots, you don’t need to do this, but if it does or some other svelte functionality that requires the component to exist in a svelte view, then this is how to do that.

You would then write a story for this “view” the exact same way you did with a component.

  1. import MyButtonView from '../views/MyButtonView.svelte';
  2. export const wrappedComponentExample = () => ({
  3. Components: MyButtonView,
  4. props: {
  5. buttonText: 'some text',
  6. rounded: true,
  7. },
  8. on: {
  9. click: (event) => {
  10. console.log('clicked', event);
  11. },
  12. },
  13. });

Each story is a single state of your component. In the above case, there are two stories for the demo button component:

  1. Button
  2. ├── With Text
  3. ├── With Emoji

Finally: Run your Storybook

Now everything is ready. Run your storybook with:

Storybook should start, on a random open port in dev-mode.