UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Next.js】Storybookを導入する

Storybook(v6.1.7)を導入する

storybook.js.org

公式にあるコマンドを実行

$ npx sb init

実行すると以下のソースが生成される

.storybook
├── main.js
└── preview.js
src/stories
├── Button.stories.tsx
├── Button.tsx
├── Header.stories.tsx
├── Header.tsx
├── Introduction.stories.mdx
├── Page.stories.tsx
├── Page.tsx
├── assets
│   ├── code-brackets.svg
│   ├── colors.svg
│   ├── comments.svg
│   ├── direction.svg
│   ├── flow.svg
│   ├── plugin.svg
│   ├── repo.svg
│   └── stackalt.svg
├── button.css
├── header.css
└── page.css
// package.json
{
  "scripts": {
    ...
    "storybook": "start-storybook -p 6006",
    "build-storybook": "build-storybook"
  },
}

TypeScript

https://storybook.js.org/docs/react/configure/typescript#gatsby-focus-wrapper

StorybookにはTypescriptサポートが組み込まれているため、特に設定を必要とせずに機能する

基本のTypescriptの設定として、 Typescriptトランスパイル用にbabel-loader、オプションでチェック用にfork-ts-checker-webpack-pluginがビルドインされている

main.jsの構成

Typescript処理の設定を調節するにはmain.jsを修正する

// .storybook/main.js

module.exports = {
  typescript: {
    check: false,
    checkOptions: {},
    reactDocgen: 'react-docgen-typescript',
    reactDocgenTypescriptOptions: {
      shouldExtractLiteralValuesFromEnum: true,
      propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
    },
  },
};
Field Framework Description Type
check All Optionally run fork-ts-checker-webpack-plugin boolean
checkOptions All Options to pass to fork-ts-checker-webpack-plugin if it's enabled See Docs
reactDocgen React Which react docgen processor to run: "react-docgen-typescript", "react-docgen", false string or false
reactDocgenTypescriptOptions React Options to pass to react-docgen-typescript-plugin if react-docgen- typescript is enabled. |See docs

グローバルスタイルの設定

https://storybook.js.org/docs/react/configure/styling-and-css

コンポーネントを表示するiframe内のスタイルはpreview.jsで行う

styled-componentsを使っているので、次のように定義する

import React from "react";
import { createGlobalStyle } from "styled-components";

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
};

const GlobalStyle = createGlobalStyle`
  ...
`;

export const decorators = [
  (Story) => (
    <>
      <GlobalStyle />
      <Story />
    </>
  ),
];

xxxx.stories.tsの置き場所(お気持ち)

ストーリーファイルは別ディレクトリにせずに同じディレクトリにした

過不足がわかりやすいように

src/client
└── components
    ├── _styleguide
    │   ├── ...
    ├── atoms
    │   ├── Icon.stories.tsx
    │   ├── Icon.jsx
    │   ├── Link.stories.tsx
    │   ├── Link.tsx
    │   ├── Price.stories.tsx
    │   ├── Price.tsx
    │   ├── Select.stories.tsx
    │   └── Select.tsx