How to Add Storybook to Gridsome [2021 Guide]

November 6, 2020 · Updated January 23, 2021 · 2 min read
rough drafts of a website design
Photo by Halacious on Unsplash

This is part seventeen of a series on building a file-based blog from scratch with Gridsome. Find the full series here.

Storybook enables component-driven development for frontend teams.

This allows you to build high-quality components by thinking about their structure and interface before integrating them into the app.

Let's integrate Storybook (6.1.15) with Gridsome (0.7.23) and see how we can use them together.

Setup

At the root of your gridsome project, run:

npx sb init --type vue

This command will install storybook, configure it for Vue and make it ready to use.

You can then start storybook with

yarn storybook

You may get an issue with an error like Module not found: Error: Can't resolve 'vue-docgen-loader'. When you see this, run yarn upgrade and it should work normally.

How to use

What you see after starting Storybook for the first time are their default examples. There is one introduction story in the mdx format, and three component stories. You find all example stories in the src/stories folder.

Read through these examples, to understand how storybook works and how you can create your own stories. The Storybook docs are great, as well as the Component Driven website.

If you follow the example of the Gridsome series on this blog, let's create a story for the ThemeSwitcher.vue component.

Create a file as src/components/ThemeSwitcher.stories.js with the following content:

import ThemeSwitcher from './ThemeSwitcher'

export default {
  title: 'Components/ThemeSwitcher',
  component: ThemeSwitcher
}

const Template = (args, { argTypes }) => ({
  props: Object.keys(argTypes),
  components: { ThemeSwitcher },
  template:
    '<theme-switcher :theme="theme" />'
})

export const Light = Template.bind({})
Light.args = {
  theme: 'theme-light'
}

export const Dark = Template.bind({})
Dark.args = {
  theme: 'theme-dark'
}

When storybook has rendered, you can open this new story and see both states: the sun and the moon icon.

Next part: Using Markdown Widgets

That’s it for this post on how to add an article series overview page to your Gridsome blog. In the next part of this series, we look at Markdown widgets and how we can use them in our blog.