Course page
Log in

You are watching a free preview. Enroll to open all 24 lessons, track progress and ask the course tutor.

Enroll for $54.99

Section 1: Storybook foundations

Installing Storybook in a component library

Article 10 min Lesson 2 of 24 Preview

Storybook installs into an existing project with a single command that detects your framework and builder and sets up sensible defaults.

Running the installer

From the root of the component library, run:

npx storybook@latest init

The installer detects React and Vite, adds the needed packages, creates a .storybook folder and adds example stories. It also adds two npm scripts: one to run Storybook in development, usually on port 6006, and one to build a static version.

Start it with:

npm run storybook

Your browser opens Storybook with the example stories. Delete the examples once you have seen them; we will write our own.

The configuration files

The .storybook folder holds two main files.

main.ts configures where stories live, which addons load and which framework is used:

import type { StorybookConfig } from '@storybook/react-vite';

const config: StorybookConfig = {
  stories: ['../src/**/*.stories.@(ts|tsx)', '../src/**/*.mdx'],
  addons: ['@storybook/addon-docs', '@storybook/addon-a11y'],
  framework: { name: '@storybook/react-vite', options: {} },
};
export default config;

preview.ts configures how stories render: global styles, decorators, parameters and default settings for all stories.

import type { Preview } from '@storybook/react-vite';
import '../src/styles/tokens.css';

const preview: Preview = {
  parameters: { layout: 'centered' },
};
export default preview;

Addon names and import paths have changed between major Storybook versions, so check the version installed in your project and its documentation if an import does not resolve.

Co locating stories

Place each story file next to its component:

src/components/Button/
  Button.tsx
  Button.module.css
  Button.stories.tsx

Co location keeps stories visible during code review. When someone changes a component, the reviewer sees whether stories changed too.

Loading global styles and fonts

Components often depend on global CSS such as tokens, resets and fonts. Import these in preview.ts so every story renders as it would in the product. Missing global styles are the most common reason a component looks different in Storybook than in the app.

Run Storybook again. The sidebar is empty, which is perfect. Next we write the first real stories.

← → switch lessons