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:
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:
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:
import { configure } from '@storybook/svelte';
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:
import MyButton from '../components/MyButton.svelte';
Component: MyButton,
props: {
buttonText: 'some text',
},
});
export const withEmoji = () => ({
Component: MyButton,
props: {
buttonText: '😀 😎 👍 💯',
},
});
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.
import MyButtonView from '../views/MyButtonView.svelte';
export const wrappedComponentExample = () => ({
Components: MyButtonView,
props: {
buttonText: 'some text',
rounded: true,
},
on: {
click: (event) => {
console.log('clicked', event);
},
},
});
Each story is a single state of your component. In the above case, there are two stories for the demo button component:
Button
├── With Text
├── 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.