2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CSF2とCSF3の違いは?これからのComponent Story Formatを学ぶ

Posted at

Storybookのバージョンが7に上がり、CSFの書き方も変わりました。
今後はCSF3で記述されることを考えると今CSF2を理解することはそれほど有意義ではないかもしれません…。

CSF2で記述されているプロジェクトに関わることもあるかと考えて、「どうかわったのか?」をインプットしたいと思いました!

CSFとは何か?

改めて、CSFとは「Component Story Format」のことでReactコンポーネントを文書化するための形式のことです。
現在ではStorybookのバージョンが変わりCSF2よりもCSF3の利用が推奨されています。

CSF2とCSF3で何が変わったのか?

主な変更点は2点で

  • コンポーネンの定義が簡素化されてシンプルに記述できるようになった
  • TypeScriptとの互換性が上がった

シンプルなコンポーネントを作成してみました。
実際のコードで比較したいと思います!

CSF2で記述した例

import React from 'react';
import { storiesOf } from '@storybook/react';
import Card from './card';

const meta = {
  title: 'Components/Card',
  component: Card,
  parameters: {
    layout: 'centered',
  },
  tags: ['autodocs'],
  argTypes: {
    title: { control: 'label' },
  },
};

storiesOf(meta.title, module)
  .add('card', () => (
    <Card
      title="cardにheadingを設定したいときに入力してください"
      children="cardのコンテンツをここに入れます。HTMLなども入れることも自由に入れることができます"
    />
  ));

CSF3で記述した例

import type { Meta, StoryObj } from '@storybook/react';
import Card from './card';

const meta = {
  title: 'Components/Card',
  component: Card,
  parameters: {
    layout: 'centered',
  },
  tags: ['autodocs'],
  argTypes: {
    title: { control: 'label' },
  },
} satisfies Meta<typeof Card>;

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

export const card: Story = {
  args: {
    title: 'cardにheadingを設定したいときに入力してください',
    children:
      'cardのコンテンツをここに入れます。HTMLなども入れることも自由に入れることができます',
  },
};

CSF2とCSF3のコードの違い

import箇所

CSF2ではstoriesOf関数をインポートしてストーリーを定義する際に利用しています。
それに対しCSF3は、@storybook/reactからtypeで指定して型情報のみをインポートしています。

metaデータの定義

今回の記述方法だとmetaデータ定義部分ではほとんど差はありませんが、最後の1行が異なっています。

 } satisfies Meta<typeof Card>;

上記のように記述しておくことでCSF2では検知できなかった必須引数の不足をエラーとして検知してくれます。

storyの定義

CSF2ではstoryの定義時にstoriesOf関数を利用して定義するのに対して、CSF3では名前つきエクスポートを利用することで完結にstoryを定義することができます。

【CSF2とCSF3の違い】まとめ

シンプルに記述できるようになったのも素晴らしいですが、TypeScriptとの互換性が上がったことで開発中のミスに気がつけるようになったのは開発体験があがるだけでなく、コードの保守・運用の面でも役立つイメージをもてました!

まだまだ、理解できていない利点はあると思いますがさらに知見を深めていきたいと思います!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?