🔨

SvelteKitにStorybookを導入する

に公開

Storybook バージョン 7 から SvelteKit の Built-in サポートが開始されました。

https://twitter.com/storybookjs/status/1631348833916702721

https://storybook.js.org/recipes/@sveltejs/kit

バージョン 6 以前では煩雑な設定が必要でしたが、7 以降ではこれらが不要となりました。
現状この 7 に対応した記事が見当たらなかったため今回メモとして残しておきます。

store 機能など SvelteKit 特有の設定はまた別記事で載せる予定です。

確認した環境

  • SvelteKit 1.0
  • Storybook 7.0
  • TypeScript 5.0

Storybook の導入

新規アプリに導入する際はこのコマンド 1 つで完結します。

$ npx storybook@latest init

すると次のようなメッセージがターミナルで表示されるはずです。
途中で Storybook の ESLint に関する質問がされますが、これは特別な理由がない限り yes でいいかと。

Need to install the following packages:
  storybook@7.0.9
Ok to proceed? (y)

 storybook init - the simplest way to add a Storybook to your project.

 Detecting project type.
    Detected Vite project. Setting builder to Vite
 Adding Storybook support to your "SvelteKit" app

added 739 packages, and audited 950 packages in 50s

190 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
.
 Preparing to install dependencies.


up to date, audited 950 packages in 1s

190 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
.
🔎 checking possible migrations..

attention => Storybook now collects completely anonymous telemetry regarding usage.
This information is used to shape Storybook's roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://storybook.js.org/telemetry


🔎 found a 'eslintPlugin' migration:
 Automigration detected ──────────────────────────────────────────────────────────────────────────────────────────────────────────╮│                                                                                                                                  ││   We've detected you are not using our eslint-plugin.                                                                            ││                                                                                                                                  ││   In order to have the best experience with Storybook and follow best practices, we advise you to install                        ││   eslint-plugin-storybook.                                                                                                       ││                                                                                                                                  ││   More info: https://github.com/storybookjs/eslint-plugin-storybook#readme                                                       ││                                                                                                                                  │╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✔ Do you want to run the 'eslintPlugin' migration on your project? … yes
✅ Adding dependencies: eslint-plugin-storybook

added 3 packages, and audited 953 packages in 2s

190 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
✅ Adding Storybook plugin to .eslintrc.cjs
✅ ran eslintPlugin migration

╭ Migration check ran successfully ────────────────────────────────────────────────────────────────────────────────────────────────╮│                                                                                                                                  ││   Successful migrations:                                                                                                         ││                                                                                                                                  ││   eslintPlugin                                                                                                                   ││                                                                                                                                  ││   ─────────────────────────────────────────────────                                                                              ││                                                                                                                                  ││   If you'd like to run the migrations again, you can do so by running 'npx storybook@next automigrate'                           ││                                                                                                                                  ││   The automigrations try to migrate common patterns in your project, but might not contain everything needed to migrate to the   ││   latest version of Storybook.                                                                                                   ││                                                                                                                                  ││   Please check the changelog and migration guide for manual migrations and more information:                                     ││   https://storybook.js.org/migration-guides/7.0                                                                                  ││   And reach out on Discord if you need help: https://discord.gg/storybook                                                        ││                                                                                                                                  ││   ─────────────────────────────────────────────────                                                                              ││                                                                                                                                  ││   You can find more information for a given dependency by running npm ls --depth=1 <package-name>                                ││                                                                                                                                  │╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯


For more information visit: https://storybook.js.org

To run your Storybook, type:

   npm run storybook

ちなみに Storybook がすでに入っている場合は次のコマンドが使えるようです。

$ npx storybook@latest upgrade

npm run storybook を叩いて、画面にこれが出れば完了です。

導入後に追加されるファイルについて

現時点(2023/5/6 時点)でまだ公式ドキュメントに記載されていない箇所もあるので、
備忘録代わりとして記載しておきます。

.storybook フォルダ

TypeScript が有効になっていると中身のファイルも自動的に ts ファイルで生成してくれます。
型定義やフレームワークの設定に Svelte 専用のものが当てられていることがわかります。

.storybook/main.ts
import type { StorybookConfig } from "@storybook/sveltekit";
const config: StorybookConfig = {
  stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
  ],
  framework: {
    name: "@storybook/sveltekit",
    options: {},
  },
  docs: {
    autodocs: "tag",
  },
};
export default config;
.storybook/preview.ts
import type { Preview } from '@storybook/svelte';

const preview: Preview = {
	parameters: {
		actions: { argTypesRegex: '^on[A-Z].*' },
		controls: {
			matchers: {
				color: /(background|color)$/i,
				date: /Date$/
			}
		}
	}
};

export default preview;

stories フォルダ

このフォルダには例となる svelte ファイルおよび stories ファイルが格納されます。
こちらも.storybook フォルダと同じく ts が有効になっていると、ts ファイルで生成されます。

stories ファイルの書き方は Next.js など他のフレームワークと一緒なので詳細は省きますが、
SvelteKit では import 先のライブラリが Svelte のものになります。

stories/Button.stories.ts
import type { Meta, StoryObj } from "@storybook/svelte";

import Button from "./Button.svelte";

// More on how to set up stories at: https://storybook.js.org/docs/svelte/writing-stories/introduction
const meta = {
  title: "Example/Button",
  component: Button,
  tags: ["autodocs"],
  argTypes: {
    backgroundColor: { control: "color" },
    size: {
      control: { type: "select" },
      options: ["small", "medium", "large"],
    },
  },
} satisfies Meta<Button>;

export default meta;
type Story = StoryObj<typeof meta>;

// More on writing stories with args: https://storybook.js.org/docs/svelte/writing-stories/args
export const Primary: Story = {
  args: {
    primary: true,
    label: "Button",
  },
};

// 以下省略

余談

package.json を見ると、Storybook を追加後、 React が追加されています。

  • react
  • react-dom

これは以下のコードを見る限り、Storybook の構造上仕方ないようです。

https://github.com/storybookjs/storybook/blob/91b4484b8a4ba3a41ddd1be37aff24ccd7335df9/code/frameworks/svelte-vite/package.json#L65

終わりに

今回は SvelteKit に公式対応された Storybook の導入部分までをまとめてみました。
まだ公式ドキュメント・チュートリアルに反映されていない部分も多く、実際に環境構築しないと不透明な部分も多い分野ですが、少しずつ情報をまとめて行きたいところです。

GitHubで編集を提案

Discussion